Skip to content

Instantly share code, notes, and snippets.

@fvisticot
Created December 24, 2019 22:43
Show Gist options
  • Save fvisticot/ca35c15c7b75e2ab88cf38c264380402 to your computer and use it in GitHub Desktop.
Save fvisticot/ca35c15c7b75e2ab88cf38c264380402 to your computer and use it in GitHub Desktop.
Stream yield async
import 'dart:async';
void main() async {
Future<int> computeCost(int val) async {
await Future.delayed(Duration(seconds: 1));
return val * 2;
}
Stream<int> generateValues1() {
return Stream.periodic(Duration(seconds: 1), (val) {
return val;
});
}
Stream<int> generateValues2() {
return Stream.periodic(Duration(seconds: 1), (val) {
return computeCost(val);
}).map((futureRes) {
futureRes.then((val) => print("Test: $val"));
});
}
Stream<int> generateValues3() async* {
int i = 0;
while (true) {
await Future.delayed(Duration(seconds: 1));
yield i++;
}
}
Stream<int> generateValues4() async* {
int i = 0;
while (true) {
await Future.delayed(Duration(seconds: 2));
final cost = await computeCost(i++);
yield cost;
}
}
Stream<int> generateValues5() async* {
yield* generateValues3();
}
final subscription=generateValues5().listen((val) => print(val));
await Future.delayed(Duration(seconds: 10));
print("Cancelling subscription");
subscription.cancel();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment