Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make websocket stream broadcast to many other pages?

I have a websocket stream being listened:

widget.channel.stream.listen((data) {
  print("!!!!new msg: $data");
  var dataJson = json.decode(data);
  print(dataJson["content"]);
  // do my job
  setState(() {
    _allAnimateMessages.insert(0, newMsg);
  });
  newMsg.animationController.forward();
});

But, when enter that page again, there was an error says: Bad state: Stream has already been listened to.

How to make it as broadcast and other pages can receive that broadcast?

like image 817
Nicholas Jela Avatar asked May 23 '18 07:05

Nicholas Jela


1 Answers

You can use broadcasts.

 //Here is the solution
 StreamController<String> streamController = new StreamController.broadcast();   //Add .broadcast here

//Now you can listen from various places
@override
void initState() {
  super.initState();

  print("Creating a StreamController...");
  //First subscription
  streamController.stream.listen((data) {
    print("DataReceived1: " + data);
  }, onDone: () {
    print("Task Done1");
  }, onError: (error) {
    print("Some Error1");
  });
  //Second subscription
  streamController.stream.listen((data) {
    print("DataReceived2: " + data);
  }, onDone: () {
    print("Task Done2");
  }, onError: (error) {
    print("Some Error2");
  });

  streamController.add("This a test data");
  print("code controller is here");

}

Font: https://medium.com/@ayushpguptaapg/using-streams-in-flutter-62fed41662e4

When using broadcasts you can have multiple listeners in the same stream.

If you simply use a stream without ".broadcast ()" you can only have one listener

like image 53
Matheus Toniolli Avatar answered Sep 30 '22 17:09

Matheus Toniolli