在 Combine iOS 中获取取消订阅的状态



我有一个简单的订阅,我的subject正在发出字符串。出于好奇,我想知道我的订阅是否被取消。

Afaik 已取消的管道将不会发送任何完成。 有没有办法做到这一点?

用例是我可以取消所有订阅并完成此操作。我可以在哪里清理东西,可能反映了这一点。

PlaygroundPage.current.needsIndefiniteExecution = true
var disposeBag: Set<AnyCancellable> = .init()
let subject = PassthroughSubject<String, Never>()
subject.sink(receiveCompletion: { completion in
switch completion {
case .failure(let error):
print("Failed with: (error.localizedDescription)")
case .finished:
print("Finished")
}
}) { string in
print(string)
}.store(in: &disposeBag)
subject.send("A")
disposeBag.map { $0.cancel() }
subject.send("B")

可以通过处理事件来实现

subject
.handleEvents(receiveCancel: {
print(">> cancelled")         // << here !!
})
.sink(receiveCompletion: { completion in
switch completion {
case .failure(let error):
print("Failed with: (error.localizedDescription)")
case .finished:
print("Finished")
}
}) { string in
print(string)
}.store(in: &disposeBag)

最新更新