【问题标题】:How to map() a Stream until it is cancelled in Dart?如何映射()一个流,直到它在 Dart 中被取消?
【发布时间】:2019-02-20 18:14:51
【问题描述】:

我有一个Stream,我从数据库查询中得到。我相信查询会运行一段时间,并在运行时产生值,所以我希望能够在项目可用时立即向用户显示。

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

我在写这篇文章时遇到了麻烦,因为我不知道如何才能获得可以在以后取消的流的订阅,同时映射其元素,以便我的映射流的使用者可以处理由原始 Stream 生成的项目。

基本上,我认为我需要CancellableStream 之类的东西,但我在 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?

【问题讨论】:

    标签: asynchronous dart


    【解决方案1】:

    我认为where(...) 使用hasPicked 的状态应该做你想做的事

    bool hasPicked = false;
    ...
    final processed = cursor.where((entry) => !hasPicked).map((entry) => process(entry));
    

    当用户选择一个时,将hasPicked 设置为true。

    【讨论】:

    • 这太棒了。谢谢。
    【解决方案2】:

    基于https://www.dartlang.org/articles/libraries/creating-streams...

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

    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;
    }
    

    【讨论】:

      猜你喜欢
      • 2020-10-24
      • 2023-01-04
      • 1970-01-01
      • 2015-04-10
      • 2018-05-11
      • 1970-01-01
      • 1970-01-01
      • 2021-08-28
      • 1970-01-01
      相关资源
      最近更新 更多