Search code examples
flutterdart-async

Flutter: Exception while trying to listen to Broadcast stream twice


I have a storage that contains a broadcast stream

 Stream<List<DeliveryModel>> get deliveriesStream {
    this._getDeliveries();
    return this._controller.stream.asBroadcastStream();
  }

and have two subscribers, once I start to listen manually,

var stream = this._deliveryRepo.deliveriesStream;
    deliveriesSubscription = stream.listen((deliveries) {
    // to do something 
});

and once via StreamBuilder

@override
  void initState() {
    super.initState();
    this.stream = this.widget.deliveriesFetcher.getDeliveriesStream();
  }

  @override
  Widget build(BuildContext context) {
    return StreamBuilder(
        stream: this.stream,
        builder: (context, snapshot) {
          // do something
        });
  }

where

@override
  Stream<List<DeliveryModel>> getDeliveriesStream() {
    return this._deliveryRepo.deliveriesStream;
  }

If I understood correctly, I subscribe to broadcast stream twice, so everything should be fine, but when I try to subscribe to the stream for the second time (via StreamBuilder), it throws an exception: Bad state: Stream has already been listened to. Any suggestions?


Solution

  • The reason is that you are creating a new BroadcastStream every time the deliveriesStream getter invokes. Try to use something like this:

    Stream<List<DeliveryModel>> _deliveriesStream;
    
    Stream<List<DeliveryModel>> get deliveriesStream {
      this._getDeliveries();
      _deliveriesStream ??= _controller.stream.asBroadcastStream();
      return _deliveriesStream;
    }