dartrxdart

Not able to listen to a broadcast Stream


My standard stream:

var stream = (StreamController<int>()..add(1)).stream;
stream.listen(print); // prints 1

My broadcast stream:

var stream = (StreamController<int>.broadcast()..add(1)).stream;
stream.listen(print); // doesn't print anything

Solution

  • Broadcast streams does not buffer events when there is no listener unlike standard streams. Declare the broadcast stream first, listen to it then add an event.

    var controller= StreamController<int>.broadcast();
    controller.stream.listen(print); 
    controller.sink.add(1); // will print 1