onMessage<T extends Message> method

StreamSubscription<T> onMessage<T extends Message>({
  1. required String name,
  2. required T constructor(
    1. List<int>
    ),
  3. required void callback(
    1. T
    ),
})

Allows callers to listen only for specific messages.

To use this, pass the name of the message, a function to create the message from binary data, and a callback to handle the message. For example,

collection.server.messages.onMessage(
  name: ScienceData().messageName,  // equals "ScienceData"
  constructor: ScienceData.fromBuffer,
  callback: (data) => print(data.co2);
)

This function returns a StreamSubscription that you can use to stop listening.

Implementation

StreamSubscription<T> onMessage<T extends Message>({
  required String name,
  required T Function(List<int>) constructor,
  required void Function(T) callback,
}) =>
  where((wrapper) => wrapper.name == name)
  .map((wrapper) => constructor(wrapper.data))
  .listen(callback);