Swift Combine 如何设置<AnyCancellable>作品? [英] Swift Combine how Set&lt;AnyCancellable&gt; works?

查看:30
本文介绍了Swift Combine 如何设置<AnyCancellable>作品?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我用这种方式定义了带有一次性 Set 的 ViewModel

I have ViewModel with disposable Set defined this way

class ViewModel { 


 private var disposables = Set<AnyCancellable>()

 func sync() { 
    repo.syncObjects()
            .handleEvents(receiveCancel: {
                print("Synced objects: CANCELED!")
            })
            .sink(receiveCompletion: { completion in
                switch completion {
                case .failure(let error):
                    print("Synced objects: \(error)")
                case .finished:
                    print("Synced objects: finished")
                }
            }) { objects in
                print("Synced objects: \(objects)")
            }.store(in: &disposables)
 }

  deinit { print("ViewModel deinit") }
}

我正在 SwiftUI 视图中的 onAppear 中调用 sync().然后我快速切换屏幕,从 SwiftUI 视图引用的 ViewModel 被 ARC 释放,就像调用 deinit 一样,但订阅似乎仍然有效,一次性引用不会取消订阅,它从网络获取数据并将它们保存在核心数据中并打印同步对象:对象, 同步对象:完成.即使我停止切换屏幕几秒钟以完成旧请求,它也保持活动状态.

I am calling sync() in onAppear in SwiftUI view. Then I am fast switching screens and ViewModel referenced from SwiftUI view is deallocated by ARC like deinit is called but subscriptions seems to remain alive and disposable reference does not cancel subscription it fetches data from Network and saved them in Core Data and prints Synced objects: objects, Synced objects: finished. And keeps being alive even when I stop switching screens for several seconds to complete old requests.

我应该手动取消 AnyCancellable 吗?不应该自动取消吗?

Should I manually cancel AnyCancellable? shouldn't it be cancelled automagically?

推荐答案

不,你不需要取消任何可取消的,因为这种对象在取消初始化时会调用方法cancel.所以你的代码是正确的.

No, you dont need to cancel any cancellable because this kind of object calls the method cancel when deinitialized. So your code is correct.

Apple 的 AnyCancellable 文档:

Apple's documentation of AnyCancellable:

AnyCancellable 实例在取消初始化时自动调用cancel()

任何可取消

这篇关于Swift Combine 如何设置<AnyCancellable>作品?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆