从其回调内部取消StreamSubscription

时间:2018-07-08 14:58:04

标签: dart dart-async

这是该情况的 (简化)场景

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

我想根据它们的内容停止收听 ,但是我对此事不屑一顾。

Stream

使用StreamSubscription streamSubscription = stream.listen((_) {}); streamSubscription.cancel(); // cancels the subscription ,我通常可以取消订阅,但无法在cancel()回调中访问streamSubscription

2 个答案:

答案 0 :(得分:3)

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

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

答案 1 :(得分:0)

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