【问题标题】:Cancel StreamSubscription from Inside its Callback从回调内部取消 StreamSubscription
【发布时间】:2018-07-08 14:58:03
【问题描述】:

这是一个(简化)场景

stream.listen((bool result) {
  if (result) {
    // should cancel the subscription
  }
});

我想停止收听基于 Stream 的内容,但我无法完全理解它以得出结论。

StreamSubscription streamSubscription = stream.listen((_) {});

streamSubscription.cancel(); // cancels the subscription

使用cancel(),我通常可以取消订阅,但我无法在listen 回调中访问streamSubscription

【问题讨论】:

    标签: dart dart-async


    【解决方案1】:

    需要拆分变量声明和初始化:

    StreamSubscription streamSubscription;
    streamSubscription = stream.listen((bool result) {
      if (result) {
        streamSubscription.cancel();
      }
    });
    

    【讨论】:

    • 我知道我以前做过!我用StreamIterator 解决了我的问题,但我认为它通常不适合作为我简化问题的答案:)
    • 你无法解决简化的场景,因为在任何地方都没有引用StreamSubscription,所以你不能取消它。您需要存储对订阅的引用,并且需要在未在引用它的行上声明的变量中执行此操作,因此此答案中的代码实际上是简化方案的最短解决方案。
    【解决方案2】:

    使用 Dart 版本 >= 2.12 引入 null safety

    StreamSubscription? s;
    s = controller.stream.listen(
      (val) {
        print(val);
        if (val == "someVal") {
          s?.cancel();
        }
      },
      onError: (e) => print("onError"),
      // This will be called on stream closed event 
      // ONLY IF the subscription is still active
      onDone: () { print("onDone"); }
    );
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-05-26
      • 2020-10-01
      • 2020-02-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-07-19
      相关资源
      最近更新 更多