events method

Stream<LiveEvent> events()

Streams the events this app posts to the nylo VM service stream.

Each call gets its own stream. The VM service subscription is shared: it's made when the first stream is listened to and cancelled when the last one is, so a command watching events inside metro live doesn't end the shell's own subscription.

Implementation

Stream<LiveEvent> events() {
  late final StreamController<LiveEvent> controller;
  StreamSubscription<JsonRpcNotification>? subscription;

  controller = StreamController<LiveEvent>(
    onListen: () async {
      subscription = client.notifications.listen((notification) {
        final LiveEvent? event = parseStreamEvent(notification, 'nylo');
        if (event != null) controller.add(event);
      }, onDone: controller.close);
      if (++_eventListeners > 1) return;
      final Future<void> listening = _nyloListening = _listenToNylo();
      try {
        await listening;
      } catch (e) {
        controller.addError(e);
      }
    },
    onCancel: () async {
      await subscription?.cancel();
      if (--_eventListeners > 0) return;
      _nyloListening = null;
      if (client.isClosed) return;
      try {
        await client.call('streamCancel', {'streamId': 'nylo'});
      } catch (_) {
        // Nothing to clean up if the app is already gone.
      }
    },
  );
  return controller.stream;
}