How to subscribe on events in SignalR in Dart?

Viewed 36

I want to subscribe on events using signal r and using sound effect when these events happens. How can I create this in Dart (I have JS code sample but don't really understand how to make it in Dart)

In Dart it looks like that. I have sample with data: data: {id: '1234', date: '2022-08-29T12:05:27.770Z', base: 'BaseNameExample', additionInfo: 'there is no example', dataId: '3fa85f64-5717-4562-b3fc-2c963f66afa6'},

and in Dart I am trying to do it like that using audioplayer:

class EventsSubsriber{
  Alarmplayer alarmplayer = Alarmplayer();

  Future<List> fetchNotifications() async {
    Logger.root.level = Level.ALL;
    Logger.root.onRecord.listen((LogRecord rec) {
      print('${rec.level.name}: ${rec.time}: ${rec.message}');
    });

    Logger? logger;

    final httpConnectionOptions = HttpConnectionOptions(
        accessTokenFactory: () => SharedPreferenceService().loginWithToken(),
        skipNegotiation: true,
        transport: HttpTransportType.WebSockets);

    final hubConnection = HubConnectionBuilder()
        .withUrl(
          'http://securelink/home',
          options: httpConnectionOptions,
        )
        .build();
    await hubConnection.start();
    List notifications= [];
    if (hubConnection.state == HubConnectionState.Connected) {
      await hubConnection
          .invoke('GetNotifications')
          .then((value) => notifications= value as List);
      await alarmplayer.Alarm(url: 'assets/notifSound.mp3', volume: 1);
      alarmplayer.IsPlaying();
    }
    hubConnection.on('GetNotifications', (arguments) {
      if (arguments!.isNotEmpty) {
        arguments == ['id'];
        arguments == ['date'];
        arguments == ['baseNameExample'];
        arguments == ['additionInfo'];
        alarmplayer.Alarm(url: 'assets/wanted.mp3', volume: 1);
        alarmplayer.IsPlaying();
      } else {
        alarmplayer.StopAlarm();
      }
    });
    // hubConnection.keepAliveIntervalInMilliseconds = 10 * 60 * 60 * 1000;
    hubConnection.onclose(({error}) {
      Logger.root.level = Level.ALL;
      Logger.root.onRecord.listen((LogRecord rec) {
        print('${rec.level.name}: ${rec.error}: ${rec.message}');
      });
      print(error);
    });
    print(notifications);
    return notifications;
  }
}

JS-code sample looks like this:

Notifications(data) {
                //console.log(data)
                this.id = data.id;
                this.date= data.date;
                this.alarm.play();
            }, 
1 Answers

Okay, I have found the solution: first of all, it is really important to check if your backend devs wrote event on websockets correctly. After all this has done, we need to create our side:

It works as usuall websocket request, so we need know which type websockets returns: Map, List, bool, String, etc and the event's name. After that I wrote this code:

  final hubConnection = HubConnectionBuilder()
        .withUrl(
          'your_url',
  
        )
        .build();
    await hubConnection.start();
    List events = [];
    hubConnection.on('EventsExample', (arguments) async {
      events = arguments as List;
    
    });

argument - return websockets event as @HKN said. In my case I need to use event's responce in my ui, so I assigned a variable with empty lists to the websocket response. But if you do not need to show anything in the user interface, then you can write inside the event just print(arguments)

Related