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

There should be cancellable versions of Stream.firstWhere etc. #248

Open
maBarabas opened this issue Jul 31, 2023 · 0 comments
Open

There should be cancellable versions of Stream.firstWhere etc. #248

maBarabas opened this issue Jul 31, 2023 · 0 comments

Comments

@maBarabas
Copy link

It would be nice if functions like Stream.firstWhere all had a cancellable version returning CancellableOperation. The existing version can not be cancelled, and only cancel their subscriptions when receiving the relevant event or an error.

The implementation could look something like:

extension _CancellableFirstWhereEx<T> on Stream<T> {
  CancelableOperation<T> cancellableFirstWhere(bool Function(T) predicate) {
    late final CancelableCompleter<T> completer;
    final subscription = listen(
      null,
      // ignore: avoid_types_on_closure_parameters
      onError: (Object e) => completer.completeError(e),
      cancelOnError: true,
    );

    completer = CancelableCompleter<T>(
      onCancel: () {
        subscription.cancel();
      },
    );

    subscription.onData((value) {
      if (predicate(value)) {
        subscription.cancel();
        completer.complete(value);
      }
    });

    return completer.operation;
  }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant