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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With