Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why does this Dart broadcast stream not accept multiple listen calls

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?

like image 675
Daniel Robinson Avatar asked May 10 '13 21:05

Daniel Robinson


1 Answers

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.

like image 166
Florian Loitsch Avatar answered Sep 21 '22 19:09

Florian Loitsch