import 'dart:async';
void main() {
var dog = Dog();
showTheDogACat(dog);
print('outside');
dog.bark();
}
class Cat{
void runAway(msg){
print("$msg I'm running away!");
}
}
class Dog{
var _barkController = StreamController();
Stream get onBark => _barkController.stream.asBroadcastStream();
void bark(){
_barkController.add("woof");
}
}
showTheDogACat(dog){
var cat = 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 2nd dog.onBark.listen
call generate Exception: stream already has subscriber? I thought broadcast streams could have many subscribers?
The getter onBark
invokes asBroadcastStream
a second time on the _barkController.stream
. The newly created broadcast-stream will try to bind to the _barkController.stream
but will fail because there is already a listener.
So yes: broadcast streams may have multiple listeners, but the asBroadcastStream
method must not be invoked multiple times on a single-subscription stream.
One solution is to cache the result of your first asBroadcastStream
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With