Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(range): ensure RangeStream is only listened to once #694

Merged
merged 1 commit into from
Oct 12, 2022
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
42 changes: 15 additions & 27 deletions lib/src/streams/range.dart
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import 'dart:async';
///
/// RangeStream(3, 1).listen((i) => print(i)); // Prints 3, 2, 1
class RangeStream extends Stream<int> {
var _isListened = false;
final Stream<int> _stream;

/// Constructs a [Stream] which emits all integer values that exist
Expand All @@ -18,36 +19,23 @@ class RangeStream extends Stream<int> {

@override
StreamSubscription<int> listen(void Function(int event)? onData,
{Function? onError, void Function()? onDone, bool? cancelOnError}) =>
_stream.listen(onData,
onError: onError, onDone: onDone, cancelOnError: cancelOnError);
{Function? onError, void Function()? onDone, bool? cancelOnError}) {
if (_isListened) {
throw StateError('Stream has already been listened to.');
}
_isListened = true;

return _stream.listen(onData,
onError: onError, onDone: onDone, cancelOnError: cancelOnError);
}

static Stream<int> _buildStream(int startInclusive, int endInclusive) {
final controller = StreamController<int>(sync: true);
StreamSubscription<int>? subscription;

controller.onListen = () {
final length = (endInclusive - startInclusive).abs() + 1;
int nextValue(int index) => startInclusive > endInclusive
? startInclusive - index
: startInclusive + index;

subscription =
Stream.fromIterable(Iterable.generate(length, nextValue)).listen(
controller.add,
onError: controller.addError,
onDone: controller.close,
);
final length = (endInclusive - startInclusive).abs() + 1;

controller.onPause = subscription!.pause;
controller.onResume = subscription!.resume;
};
controller.onCancel = () {
final future = subscription?.cancel();
subscription = null;
return future;
};
int nextValue(int index) => startInclusive > endInclusive
? startInclusive - index
: startInclusive + index;

return controller.stream;
return Stream.fromIterable(Iterable.generate(length, nextValue));
}
}