Last active
January 15, 2024 16:07
-
-
Save kpsroka/c6f58ef942fb413883942baff2f4de57 to your computer and use it in GitHub Desktop.
fakeAsync vs async*
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import 'dart:async'; | |
import 'package:fake_async/fake_async.dart'; | |
import 'package:test/test.dart'; | |
Future<int> firstEven(Stream<int> numberStream) => | |
numberStream.firstWhere((element) => element.isEven); | |
void main() { | |
void runTest(Stream<int> stream, StreamSink<int> sink) { | |
fakeAsync((async) { | |
final completer = Completer<int>(); | |
firstEven(stream).then(completer.complete); | |
async.flushMicrotasks(); | |
expect(completer.isCompleted, false); | |
sink.add(1); | |
sink.add(3); | |
sink.add(5); | |
async.flushMicrotasks(); | |
expect(completer.isCompleted, false); | |
sink.add(2); | |
async.flushMicrotasks(); | |
expect(completer.isCompleted, true); | |
}); | |
} | |
test('test with StreamController', () { | |
final controller = StreamController<int>(); | |
runTest(controller.stream, controller.sink); | |
}); | |
test('test with StreamController.broadcast', () { | |
final controller = StreamController<int>.broadcast(); | |
runTest(controller.stream, controller.sink); | |
}); | |
test('test with async* generator', () { | |
final controller = StreamController<int>(); | |
runTest( | |
() async* { | |
yield* controller.stream; | |
}(), | |
controller.sink, | |
); | |
}); | |
test('test with asyncExpand', () { | |
final controller = StreamController<int>(); | |
runTest( | |
Stream.fromFuture(Future.value()).asyncExpand((_) => controller.stream), | |
controller.sink, | |
); | |
}); | |
test('test with populating another controller', () { | |
final controller = StreamController<int>(); | |
runTest( | |
() { | |
final anotherController = StreamController<int>(); | |
late final StreamSubscription<int> subscription; | |
subscription = controller.stream.listen( | |
anotherController.add, | |
onDone: () => subscription.cancel(), | |
); | |
return anotherController.stream; | |
}(), | |
controller.sink, | |
); | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment