Asynchronous 如何映射()流直到它在Dart中被取消?

Asynchronous 如何映射()流直到它在Dart中被取消?,asynchronous,dart,Asynchronous,Dart,我有一个从数据库查询得到的流。我相信查询将运行一段时间,在运行时生成值,因此我希望能够在项目可用时立即向用户显示这些项目 但是一旦用户选择了一个项目,我希望流被取消 我在写这篇文章时遇到了困难,因为我不知道如何既能获得对流的订阅(稍后可以取消),又能同时映射到它的元素,以便映射流的使用者可以处理原始流生成的项目 基本上,我认为我需要像cancelablestream这样的东西,但我在Dart SDK中没有看到类似的东西 到目前为止,我已经尝试过类似的方法: final subscription

我有一个从数据库查询得到的
流。我相信查询将运行一段时间,在运行时生成值,因此我希望能够在项目可用时立即向用户显示这些项目

但是一旦用户选择了一个项目,我希望流被取消

我在写这篇文章时遇到了困难,因为我不知道如何既能获得对流的订阅(稍后可以取消),又能同时映射到它的元素,以便映射流的使用者可以处理原始流生成的项目

基本上,我认为我需要像
cancelablestream
这样的东西,但我在Dart SDK中没有看到类似的东西

到目前为止,我已经尝试过类似的方法:

final subscription = cursor.listen((entry) => process(entry));
// now I can cancel the subscription when needed, but how to
// return the processed items to the caller?

final processed = cursor.map((entry) => process(entry));
// now I have the processed Stream I wanted, but how can I cancel it?
我认为,
where(…)
使用
hasPicked的状态应该做你想做的事

bool hasPicked = false;
...
final processed = cursor.where((entry) => !hasPicked).map((entry) => process(entry));
当用户选择了一个后,根据以下内容将
hasPicked
设置为
true

下面是一个可取消流的简单实现:

class CancellableStream<T> {
  final Stream<T> _originalStream;
  bool _isCancelled = false;

  CancellableStream(this._originalStream);

  Stream<T> get stream async* {
    await for (final item in _originalStream) {
      if (_isCancelled) break;
      yield item;
    }
  }

  void cancel() => _isCancelled = true;
}
类可取消流{
最终流——原始流;
bool _isCancelled=false;
可取消流(此.\u原始流);
流获取流异步*{
等待(原始流程中的最终项目){
如果(取消)中断;
收益项目;
}
}
void cancel()=>\u isCancelled=true;
}

这太棒了。谢谢