add static method

void Function() add(
  1. Client client,
  2. String method,
  3. Future<void> handler(
    1. Map<String, dynamic> params
    )
)

Adds handler for method and returns a function that removes it.

A listener that throws does not stop the others — one consumer's bad handler must not silence every other view on the same device.

Implementation

static void Function() add(
  Client client,
  String method,
  Future<void> Function(Map<String, dynamic> params) handler,
) {
  final byMethod = _of(client);
  final listeners = byMethod.putIfAbsent(method, () {
    // First listener for this method on this client: take the single slot.
    client.onNotification(method, (params) async {
      final current = _of(client)[method];
      if (current == null) return;
      for (final l in List<_Listener>.of(current)) {
        try {
          await l.handler(params);
        } catch (_) {
          // Deliberately swallowed — see the class doc.
        }
      }
    });
    return <_Listener>[];
  });

  final listener = _Listener(handler);
  listeners.add(listener);
  return () {
    final current = _of(client)[method];
    current?.remove(listener);
  };
}