I have, for example, this simple code:
//create stream with numbers from 1 to 100, delayed by 10sec duration
Stream<int> countStream() async* {
for (int i = 1; i <= 100; i++) {
yield i;
sleep(Duration(seconds: 10));
}
}
void main() async {
var x = await countStream().firstWhere((element) => element == 1); //here Im waiting for number 1
print(x);
}
The problem is that firstWhere does not exit right after the yield of 1, but after the yeild of 2, and print is holded for 10 seconds.
Why? In my real life App, I have websocket stream that is transformed to message stream, and waiting for specific message. But because the websocket stream does not yield another message, firstWhere hangs.
Here is my original code:
Stream<Message> lines() async* {
var partial = '';
await for (String chunk in ws!) { //ws is WebSocket
var lines = chunk.split('\n');
lines[0] = partial + lines[0];
partial = lines.removeLast();
for (final line in lines) {
var msg = Message.parse(line); //Message.parse returns CodeMessage object
if (msg != null) yield msg;
}
}
}
//at some place in code this hangs because last arrived message is CodeMessage
var msg = await lines().firstWhere((obj) => obj is CodeMessage);
print(msg);
Is there another way to do this or where I am wrong?