steind.VY
steind.VY

Reputation: 338

how to listen to one stream on two screens

Error: Bad state: Stream has already been listened to. I have a screen in which there is a StreamBuilder listening to the stream and I want to listen to the same stream on another screen, but it gives an error, I try to listen like this (I store the streams in the provider using a card and get access by keys because I didn't want to duplicate some code):

final stream = objectStateInfoModelProvider.objectStateInfoProvider[obj]!
        .asBroadcastStream(
      onListen: (subscription) async {
        subscription.resume();
      },
    );
    stream.listen(
      (event) {
        setState(() {
          dataFromStream = event;
        });
      },
    );

Upvotes: 0

Views: 1712

Answers (1)

steind.VY
steind.VY

Reputation: 338

On the advice from the comment, I made a broadcast stream outside, and everything works:

final broadcastStream = stream.asBroadcastStream(
      onCancel: (subscription) {
        subscription.pause();
      },
      onListen: (subscription) {
        subscription.resume();
      },
    );

Upvotes: 3

Related Questions