Swift Combine闭包内部的弱vs无主



我不明白在Combine闭包中使用self的正确方法

class ViewModel {
var requestPublisher = PassthroughSubject<Void, Never>()
var nextPageAvailabe = true
private var subscriptions = Set<AnyCancellable>()
init() {
setupSubscriptions()
}
setupSubscriptions() {
requestPublisher
.filter { _ in self.nextPageAvailabe }
.sink(receiveValue: {
print("Received request")  
}).store(in: &subscriptions)
}
}

从父类执行的requestPublisher.send()。使用.filter { _ in self.nextPageAvailabe }会导致内存泄漏。所以我需要在filter {}中使用[weak self][unowned self]。两者都解决了内存泄漏问题,但我不明白正确的方法。我读了几篇文章,但都找不到答案。那么在Combine闭包中使用self的正确方法是什么呢?

weak无疑是一条不错的选择:您只需要一个可选的self。当一个weak变量被释放时,它就变成了零。

应该尽可能避免使用unowned,因为它在运行时不安全:它与weak类似,但结果不是可选的。因此,如果你试图在一个无主变量发布后使用它,应用程序就会崩溃。

setupSubscriptions() {
requestPublisher
.filter { [weak self] _ in self?.nextPageAvailabe ?? false }
// I have put `?? false` because I suppose that if self is nil, then page is not available...
.sink(receiveValue: {
print("Received request")  
}).store(in: &subscriptions)
}

最新更新