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

Get status of cancellation of my subscription in Combine iOS

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

据我所知,已取消的管道不会发送任何完成。 有什么方法可以做到这一点?

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

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 { [=11=].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)

backup