Why does this Dart broadcast stream not accept multiple calls to listen to

import 'dart:async'; void main() { var dog = new Dog(); showTheDogACat(dog); print('outside'); dog.bark(); } class Cat{ void runAway(msg){ print("$msg I'm running away!"); } } class Dog{ var _barkController = new StreamController(); Stream get onBark => _barkController.stream.asBroadcastStream(); void bark(){ _barkController.add("woof"); } } showTheDogACat(dog){ var cat = new Cat(); dog.onBark.listen((event)=>cat.runAway(event)); dog.onBark.listen((event)=>print(event)); //why Exception: Stream already has subscriber? print('inside'); dog.bark(); } 

why does the second call to dog.onBark.listen an exception: does the thread already have a subscriber? I thought there could be a lot of subscribers to broadcast streams?

+4
source share
1 answer

The onBark getter second time calls asBroadcastStream on _barkController.stream . A newly created broadcast stream will try to associate with _barkController.stream , but will fail because there is already a listener.

So, yes: there can be several listeners in broadcast streams, but the asBroadcastStream method asBroadcastStream not be called several times in a stream with one subscription.

One solution is to cache the result of your first asBroadcastStream .

+5
source

Source: https://habr.com/ru/post/1480173/


All Articles