on<T extends DataObject> method

void on<T extends DataObject>(
  1. MessageHandler<Message<T>> handler
)

Registers a handler for when a Message of type T is received from a connection.

Implementation

void on<T extends DataObject>(MessageHandler<Message<T>> handler) {
  _subscriptions.add(
    packets.where((packet) => packet.data is T).map((packet) {
      final connection = _findExistingConnection(packet.address) ??
          Connection(clientSalt: 0, serverSalt: 0, address: packet.address);

      // Check if the connection is known and confirmed, if it is known but
      // not confirmed set it to confirmed.
      final index = _connections.indexOf(connection);
      if (index != -1 && !_confirmedConnections[index]) {
        _confirmedConnections[index] = true;
      }
      return Message<T>(connection, packet.data as T);
    }).listen(handler),
  );
}