【问题标题】:How to stop the subscription of a stream of a singleton class?如何停止订阅单例类的流?
【发布时间】:2023-03-30 04:14:01
【问题描述】:

如何停止订阅单例类的流,并且在重新创建订阅时不继续该流的数据?

class MyClass {
  static MyClass _instance;

  factory MyClass() {
    _instance ??= MyClass._internal();
    return _instance;
  }

  MyClass._internal();

  final BehaviorSubject<Status> _streamController = BehaviorSubject<Status>();
  Stream<Status> get stream => _streamController.stream;
  Function(Status) get sink => _streamController.sink.add;

  StreamSubscription subscriptionImage;

  void dispose() {
    _streamController?.close();
  }

  void listen() {
    subscriptionImage = stream.listen((Status statusAnalysis) async {
      if (statusAnalysis.saving) {
        try {
          await patch(statusAnalysis);
        } on MyException catch (e) {}
      }
    });
  }
}

【问题讨论】:

    标签: flutter stream subscription


    【解决方案1】:

    只需在前面添加subscriptionImage?.cancel();

    subscriptionImage = stream.listen((Status statusAnalysis){...});
    

    并且您将确保在创建新订阅之前取消之前的订阅(如果有)。

    【讨论】:

    • 该流将图像发送到服务,我没有在小部件中使用它,而是在一个类中使用它,但由于某种原因取消订阅后数据流继续其过程并且不会被丢弃
    • 我看到当我再次调用这个单例类的listen方法时,里面的代码被执行了
    • 在被取消和重新订阅后它可以被执行的唯一方法,这是因为异步调用可能已经在进行中,尽管取消了订阅,你实际上不能取消正在进行的调用。你可能想看看CancelableOperation
    • 我用 Cancelable Operation 进行了测试,但结果相同,最后它最终执行了所有操作
    猜你喜欢
    • 2015-05-31
    • 1970-01-01
    • 1970-01-01
    • 2014-12-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多