Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flutter- How to get last value from Stream<String> without RxDart?

Need to know whether I can get last value from Stream without using third party library.

The first​ way I tried, when I can sending the value to stream in 'changeEmail', I can store the newValue in some variable in my BLoC. Is it correct?

The second way I tried, is adding a listener, that will also do the same job as above and I need to store the newValue in some variable.

I have SteamController:

final _emailController = StreamController<String>.broadcast();

Have gitters:

Stream<String> get email => _emailController.stream; // getting data from stream

get changeEmail => _emailController.sink.add; // sending data to stream

like image 700
Ankur Prakash Avatar asked Jan 22 '19 13:01

Ankur Prakash


1 Answers

you can not do that directly. to get the last value from a stream you need either to finish the stream first or to cache every last value added to the stream.

//close the stream and get last value:
streamController1 = new StreamController();
streamController1.add("val1");
streamController1.add("val2");
streamController1.add("val3");
streamController1.close();
streamController1.stream.last.then((value) => print(value)); //output: val3

//caching the added values:
streamController1 = new StreamController.broadcast();
String lastValue;
streamController1.stream.listen((value) {
  lastValue = value;
});
streamController1.add("val1");
streamController1.add("val2");
streamController1.add("val3");
Future.delayed(Duration(milliseconds: 500), ()=> print(lastValue)); //output: val3
like image 169
evals Avatar answered Nov 18 '22 18:11

evals