Santo Shakil
Santo Shakil

Reputation: 1052

How to check if any active Stream has already been listened to?

Is there any way to check if there is any active Stream that has already been listened to or not in Dart/Flutter?

Suppose there is a Stream that has been listened to on one Screen. But, I need to listen to that Stream on another screen. So that I need to check if there is any active stream that has been already listened to or not.

Upvotes: 4

Views: 5255

Answers (1)

Sahil Sonawane
Sahil Sonawane

Reputation: 1396

You've to use StreamController in order to check if the stream's been listened to already by using StreamController's handy hasListener getter.

Here's minimal sample code to understand:

StreamController controller = StreamController();
controller.addStream(getNumbersAsStream());

controller.stream.listen((e) => print(e));
if (!controller.hasListener) {
  controller.stream.listen((e) => print(e));
} else {
  print("Stream has already been listened");
}

Upvotes: 8

Related Questions