检查 StreamSubscription 是否被取消

Check if StreamSubscription is canceled

简单来说:

如何检查 StreamSubscription 是否已取消?

没有

_myCustomSub.isCanceled

看来您必须使用以下两种方法之一:

  1. onDone method - 并在单独的变量中保留流是否已关闭,或者..
  2. cancel method - 和 await 表示 StreamSubscription 已取消的未来。

不知道还有什么其他方法。

我想这可能是您要找的:

final streamController = StreamController();
streamController.onCancel = (){};

根据文档:Creating streams in Dart

Waiting for a subscription

To be notified of subscriptions, specify an onListen argument when you create the StreamController. The onListen callback is called when the stream gets its first subscriber. If you specify an onCancel callback, it’s called when the controller loses its last subscriber.

Final hints

The onListen, onPause, onResume, and onCancel callbacks defined by StreamController are called by the stream when the stream’s listener state changes

此外,这可能会有所帮助:

//Whether there is a subscriber on the [Stream]
streamController.hasListener

是的,正如其他人所说,没有办法检查流订阅是否被取消,这有点蹩脚。我猜你没有权限访问 StreamController,所以这是我的两个选择。

  1. _myCustomSub 设置为 null 作为取消订阅的标志并采取相应措施。

  2. 另一种方法是将 bool 值 (isSubCanceled) 与 _myCustomSub 变量放在一起,并使用它代替 _myCustomSub.isCanceled.

我 运行 遇到过类似的情况,我的解决方案是让我的 StreamSubscription 可以为 null,并在 cancel() 之后将其设置为 null。

await _newAlertsStreamSubscription?.cancel().then((_) {
     _newAlertsStreamSubscription = null;
});