Luke Pighetti
Luke Pighetti

Reputation: 4841

Awaiting first stream event as a future?

I am setting up a stream and would like to return the first value as a Future.

I would like to do this because the first value is needed to render some components, but it will continue to update the components afterwards.

How can one achieve this in dart?

Upvotes: 1

Views: 150

Answers (2)

Luke Pighetti
Luke Pighetti

Reputation: 4841

The correct way to do this is to use a broadcasting stream which can have multiple listeners and be closed/opened multiple times.

StreamController controller = StreamController.broadcast();
controller.add(foo);

controller.listen((var e) {
    print('new event $e');
});

controller.first.then((var e) {
    print('first event $e');
})

Upvotes: 0

Günter Zöchbauer
Günter Zöchbauer

Reputation: 657376

myStream.first

does return a Future with the first value

update

according to the comments below

var isFirst = true;
var completer = new Completer<Object>();
myStream.listen((event) {
  if(isFirst) {
    isFirst = false;
    completer.complete(event);
  } 
  setState(() => foo = event);
});
return completer.future;

Upvotes: 2

Related Questions