mirror of
https://gitlab.com/nkming2/nc-photos.git
synced 2025-02-24 10:28:50 +01:00
Utility fn for stream
This commit is contained in:
parent
c98482d4c5
commit
c544070236
2 changed files with 54 additions and 0 deletions
|
@ -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;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
29
app/test/stream_extension_test.dart
Normal file
29
app/test/stream_extension_test.dart
Normal 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]);
|
||||
}
|
Loading…
Reference in a new issue