asStream method

Stream<Datagram?> asStream({
  1. Duration? timeout,
})

Tells the UDP instance to listen for incoming messages.

Optionally, a timeout can be specified. if it is, the UDP instance stops listening after the duration has passed. The instance is closed too, making the instance unusable after the timeout runs out.

Whenever new data is received, it is bundled in a Datagram and pushed into the stream.

Returns a Stream that can be listened to.

Implementation

Stream<Datagram?> asStream({Duration? timeout}) {
  _streamController ??= StreamController<Datagram>();

  _udpBroadcastStream ??= (_streamController as StreamController<Datagram?>)
      .stream
      .asBroadcastStream();

  if (_socket == null || _closed) return _udpBroadcastStream!;

  if (_socketBroadcastStream == null) {
    _socketBroadcastStream = _socket!.asBroadcastStream();

    var streamSubscription = _socketBroadcastStream!.listen((event) {
      if (event == RawSocketEvent.read) {
        (_streamController as StreamController<Datagram?>)
            .add(_socket!.receive());
      }
    });

    if (!_streamSubscriptions.contains(streamSubscription)) {
      _streamSubscriptions.add(streamSubscription);
    }
  }

  if (timeout == null) return _udpBroadcastStream!;

  Future.delayed(timeout).then((value) => close());

  return _udpBroadcastStream!;
}