从回调内部取消 StreamSubscription

Cancel StreamSubscription from Inside its Callback

这是一个(简化)场景的情况:

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

我想停止收听 Stream 基于它的内容,但我无法全神贯注地得出结论。

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

streamSubscription.cancel(); // cancels the subscription

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

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

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

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