findPeers method

  1. @override
Future<Stream<AddrInfo>> findPeers(
  1. String ns, [
  2. List<DiscoveryOption> options = const []
])
override

Discovers peers providing a service

Implementation

@override
Future<Stream<AddrInfo>> findPeers(String ns, [List<DiscoveryOption> options = const []]) async {
  if (!_isRunning) {
    await start();
  }

  final controller = StreamController<AddrInfo>();

  // Create a notifee that will forward discovered peers to the stream
  final streamNotifee = _StreamNotifee(controller);

  // Store the original notifee
  final originalNotifee = _notifee;

  // Create a composite notifee that will notify both the original notifee and the stream
  final compositeNotifee = _CompositeNotifee([
    if (originalNotifee != null) originalNotifee,
    streamNotifee,
  ]);

  // Set up a subscription to handle cleanup when the stream is closed
  controller.onCancel = () {
    // If the stream is closed, we don't need to forward discovered peers to it anymore
    // But we still want to notify the original notifee
    notifee = originalNotifee;
  };

  // Set the composite notifee as the current notifee
  notifee = compositeNotifee;

  return controller.stream;
}