Skip to content

Instantly share code, notes, and snippets.

@kpsroka
Last active January 15, 2024 16:07
Show Gist options
  • Save kpsroka/c6f58ef942fb413883942baff2f4de57 to your computer and use it in GitHub Desktop.
Save kpsroka/c6f58ef942fb413883942baff2f4de57 to your computer and use it in GitHub Desktop.
fakeAsync vs async*
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