使用下面的代码时,要使用Combine。
考虑到在 https://developer.apple.com/documentation/combine/anycancellable 中已经说明:
var cancellables: [AnyCancellable] = []
func loadItems(tuple : (name : String, imageURL : URL)) {
URLSession.shared.dataTaskPublisher(for: tuple.imageURL)
.sink(
receiveCompletion: {
completion in
switch completion {
case .finished:
break
case .failure( _):
return
}},
receiveValue: { data, _ in DispatchQueue.main.async { [weak self] in self?.displayFlag(data: data, title: tuple.name) } })
.store(in: &cancellables)
}
我们不需要像下面这样在deinit
中调用cancel
deinit {
cancellables.forEach {
$0.cancel()
}
}
考虑到在 https://developer.apple.com/documentation/combine/anycancellable 中已经说明:
当取消 Cancel 时,AnyCancellable 实例会自动调用 cancel()。
既然我们不需要在 deinit 中进行释放,那么 Combine 是否可以在 struct
中使用,而不是 class
?
struct
中使用 Combine(我假设你的意思是订阅 Combine 发布者)并没有固有的问题。它会被解除初始化。但是,如果你尝试在.sink
中使用self
,就会遇到问题。 - New DevAnyCancellation
仍然会自动释放,没有deinit
,对吗? - ElyeAnyCancellable
的所有者消失,可取消订阅也将随之消失。它不会因为引用是由类、结构体(甚至闭包)持有而有所区别。 - CristikAnyCancellable
使用了什么机制来确定它可以被释放。如果它使用class
的deinit
,那么它在struct
中就不起作用。如果它使用其他机制,也适用于类和结构体,那么它们应该对两者都起作用。 - Elye