tareq3
2/16/2020 - 3:52 PM

Flutter stream

Basic Stream:

Stream is same as Observable in Rx

create a new stream

never forgot to close a stream in dispose

var mStream = new StreamController();

with fixed type:

var mStream = new StreamController<String>();
//else
StramController<String> mStream = new StreamController<String>();
//else
StreamController<String> mStream = new StreamController();
//Note: For fixed type Stream you need to provide type on transform handleData arguments

add new value in stream

mStream.sink.add("Tareq");
//
mStream.add("Islam");

Listen/Observe to Stream or Observable

mStream.listen(
(item) { print(item)},
onError: (err) => print(err);
);

Transform Stream:

var mTransform== new StreamTransformer.fromHandlers(
   handleData: (String item , sink){
      if(item !="Tareq"){
        sink.add(item +" rakib");
      }else{
        sink.addError("item is not right");
      }
   },

 );

Convert Future into Stream

Stream<String> stream = new Stream.fromFuture(getData());
  print("Created the stream");

  stream.listen((data) {
    print("DataReceived: "+data);
  }, onDone: () {
    print("Task Done");
  }, onError: (error) {
    print("Some Error");
  });

There are two type of stream

1. Single Subscription Stream

only single subscriber available. {Default in Dart}

StreamController<String> streamController = new StreamController();

2. Broadcast Stream

multiple subscriber available.

StreamController<String> streamController = new StreamController.broadcast();