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

1

10

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

Arak answered 22/1, 2019 at 13:59 Comment(3)
I think it's best to use rxdart. There are many use cases where it's cumbersome without all the transformers it provides.Unspent
Yeah, that's true, but I wanted to know how Google wants the developer to solve such problems as rxdart is the third party. So you think storing last value in the separate variable is good?Arak
I guess I'd build a class that wraps or extends Stream so that it provides this feature in a reusable way (like rxdart does ;-) ).Unspent
T
2

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
Turfman answered 21/9, 2021 at 11:55 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.