【问题标题】:Check if StreamSubscription is canceled检查 StreamSubscription 是否被取消
【发布时间】:2020-02-24 13:53:47
【问题描述】:

简单来说:

如何检查 StreamSubscription 是否被取消?

没有

_myCustomSub.isCanceled

【问题讨论】:

  • 你能多贴一点你的代码吗?

标签: flutter dart rxdart


【解决方案1】:

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

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

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

【讨论】:

    【解决方案2】:

    我认为这可能是您正在寻找的:

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

    根据文档:Creating streams in Dart

    Waiting for a subscription

    要收到订阅通知,请指定 onListen 参数 创建流控制器。 onListen 回调在 流获得它的第一个订阅者。如果你指定一个 onCancel 回调, 当控制器失去最后一个订阅者时调用它。

    Final hints

    由定义的 onListen、onPause、onResume 和 onCancel 回调 StreamController 在流的侦听器时由流调用 状态变化

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

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

    【讨论】:

      【解决方案3】:

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

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

      不知道还有什么办法。

      【讨论】:

      • 嗯,这有点可悲。尽管如此,还是感谢您的贡献
      猜你喜欢
      • 2016-08-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多