Reputation: 3943
I have a stream that yields CallEvent
objects. I want to call this stream but I'm interested in one particular event and want to consume it as a future. Is this possible?
Pseudo code of what I'm trying to achieve:
final Stream<CallEvent> aStreamOfEvents = repo.getEvents();
// However of this stream im only interested in the `ResponseEvent`
final Future<ResponseEvent> response =
aStreamOfEvents.filter((event) { event is ResponseEvent}).toFuture()
Is this possible and if yes how?
Upvotes: 1
Views: 145
Reputation: 10935
final response = aStreamOfEvents.firstWhere((e) => e is ResponseEvent);
response
is a Future<CallEvent>
above, so if you need a Future<ResponseEvent>
you'd need something like:
final response = aStreamOfEvent
.firstWhere((e) => e is ResponseEvent)
.then((e) => e as ResponseEvent);
Or, alternatively, if you use package:stream_transform
.
final response = aStreamOfEvent
.transform(whereType<ResponseEvent>())
.first
If the Stream
closes without emitting a ResponseEvent
then the future will complete with an error in all of these cases. The specific error will depend on which pattern you chose.
Upvotes: 3