Skip to content

Instantly share code, notes, and snippets.

@noboru-i
Last active September 7, 2022 07:48
Show Gist options
  • Save noboru-i/b377d55179434ad533d834d6fedb937d to your computer and use it in GitHub Desktop.
Save noboru-i/b377d55179434ad533d834d6fedb937d to your computer and use it in GitHub Desktop.
Check `await for` + stream works

Check await for + stream works

Created with <3 with dartpad.dev.

  • If we use _handle1, consume the message synchronous.
  • If we use _handle2, consume the message parallel.
import 'dart:async';
void main() {
final controller = StreamController<String>();
_handle1(controller.stream);
// _handle2(controller.stream);
controller.sink.add('message 1');
controller.sink.add('message 2');
controller.sink.add('message 3');
}
// output: "start:message 1" -> 2 seconds -> "end:message 1" -> "start:message 2" -> 2 seconds -> ...
Future<void> _handle1(Stream<String> stream) async {
await for (var value in stream) {
await _testLongProcess(value);
}
}
// output: "start:message 1" -> "start:message 2" -> "start:message 3" -> 2 seconds -> "end:message 1" -> "end:message 2" -> ...
Future<void> _handle2(Stream<String> stream) async {
stream.listen((data) async => await _testLongProcess(data));
}
Future<void> _testLongProcess(String message) async {
print('_testLongProcess start:$message');
await Future.delayed(const Duration(seconds: 2));
print('_testLongProcess end :$message');
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment