iOS Swift组合:取消Set< AnyCancellable> [英] iOS Swift Combine: cancel a Set<AnyCancellable>

查看:239
本文介绍了iOS Swift组合:取消Set< AnyCancellable>的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我将可取消集存储到ViewController中:

If I have stored a cancellable set into a ViewController:

private var bag = Set<AnyCancellable>()

其中包含多个订阅.

1-我应该在deinit中取消订阅吗?还是自动完成工作?

1 - Should I cancel subscription in deinit? or it does the job automatically?

2-如果是,我如何取消所有存储的订阅?

2 - If so, how can I cancel all the stored subscriptions?

bag.removeAll() is enough?

还是我应该遍历该集合并逐个取消所有订阅?

or should I iterate through the set and cancel all subscription one by one?

for sub in bag {
   sub.cancel()
}

Apple表示订阅一直有效,直到存储的AnyCancellable在内存中为止.所以我想用bag.removeAll()取消可取消对象就足够了,不是吗?

Apple says that the subscription is alive until the stored AnyCancellable is in memory. So I guess that deallocating the cancellables with bag.removeAll() should be enough, isn't it?

推荐答案

尝试创建管道,并且将可取消对象存储在某些状态变量中.您会发现管道在遇到异步操作后立即停止.这是因为ARC已清除了Cancelableable,因此它被自动取消了.因此,如果释放所有对管道的引用,则无需在管道上调用cancel.

Try creating a pipeline and not storing the cancellable in some state variable. You’ll find that the pipeline stops as soon as it encounters an async operation. That’s because the Cancellable was cleaned up by ARC and it was thus automatically cancelled. So you don’t need to call cancel on a pipeline if you release all references to it.

文档:

AnyCancellable实例在初始化后会自动调用cancel().

An AnyCancellable instance automatically calls cancel() when deinitialized.

这篇关于iOS Swift组合:取消Set&lt; AnyCancellable&gt;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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