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

Omatt
  • 8,564
  • 2
  • 42
  • 144
Ankur Prakash
  • 1,417
  • 4
  • 18
  • 31
  • I think it's best to use `rxdart`. There are many use cases where it's cumbersome without all the transformers it provides. – Günter Zöchbauer Jan 22 '19 at 14:02
  • 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? – Ankur Prakash Jan 22 '19 at 14:08
  • 3
    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 ;-) ). – Günter Zöchbauer Jan 22 '19 at 14:10

1 Answers1

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
evals
  • 1,750
  • 2
  • 18
  • 28