Notes by Lesnitsky Subscribe

#dart ยท 2020-06-01 02:52 PM Twitter Logo

Dart streams: how to pass a stream to another handler starting at exact item

Imagine you're processing a stream of entities with an await for-in loop

await for (var item in stream) {
doSomething(item)
}

and you need to pass the stream to some other function

await for (var item in stream) {
doSomething(item);
if (condition) {
doSomethingWithStream(stream);
}
}

Since you're iterating over a stream of items in a loop, doSomethingWithStream function will only get items after the most recent processed item.

How to create a new stream which starts with the current item?

You can do this with a simple async* function

Stream<T> prepend<T>(T item, Stream<T> stream) async* {
yield item;
yield* stream;
}