Get status of cancellation of my subscription in Combine iOS

Viewed 1042

I have this simple subscription where my subject is eminting strings. Just for curiosity I would like to know if my subscription is cancelled.

Afaik a pipeline that has been cancelled will not send any completions. Are there some ways do achieve this?

The use case would be that I can cancel all subscriptions and receive a completion on this. Where I can clean up stuff a reflect this probably.

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")
1 Answers

It is possible via handling events

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)
Related