Utility fn for stream

This commit is contained in:
Ming Ming 2022-07-25 18:31:06 +08:00
parent c98482d4c5
commit c544070236
2 changed files with 54 additions and 0 deletions

View file

@ -1,3 +1,28 @@
extension StreamExtension<T> on Stream<T> {
Stream<U> whereType<U>() => where((event) => event is U).cast<U>();
/// Creates a new stream from this stream that emits 1 element per [count]
/// elements
///
/// For a stream containing [A, B, C, D, E, F, G], return a new stream
/// containing [A, C, E, G] when [count] == 2
///
/// If [count] == 1, the returned stream is practically identical to the
/// original stream
Stream<T> per(int count) async* {
assert(count > 0);
if (count <= 1) {
yield* this;
} else {
var i = 0;
await for (final e in this) {
if (i == 0) {
yield e;
}
if (++i >= count) {
i = 0;
}
}
}
}
}

View file

@ -0,0 +1,29 @@
import 'package:nc_photos/stream_extension.dart';
import 'package:test/test.dart';
void main() {
group("StreamExtension", () {
group("per", () {
test("count = 1", _perCount1);
test("count = 2", _perCount2);
});
});
}
Future<void> _perCount1() async {
final stream = () async* {
for (var i = 0; i < 10; ++i) {
yield i;
}
}();
expect(await stream.per(1).toList(), [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]);
}
Future<void> _perCount2() async {
final stream = () async* {
for (var i = 0; i < 10; ++i) {
yield i;
}
}();
expect(await stream.per(2).toList(), [0, 2, 4, 6, 8]);
}