iosswiftrx-swiftcombineanycancellable

How do I handle cancelling of publishers in Combine's Future functions?


In RxSwift you can create a reactive function something like this:

func aFunc() -> Observable<Void> {
    return Observable.create({ emitter in
        let disposable = Observable
            .combineLatest(someObservable,
                           someOtherObservable)
                .subscribe(onNext: { responseA, responseB in
                    // do stuff
                })

                return Disposables.create {
                    disposable.dispose()
                }
            })
        }

In Combine you can achieve similar results using Future:

func aFunc() -> Future<Void, Error> {
    return Future { promise in
        somePublisher
            .combineLatest(someObservable,
                           someOtherObservable)
                .sink{ responseA, responseB in
                    // do stuff
                }
            })
        }

The thing I don't quite get is that the Future doesn't seem to return its equivalent of RxSwift's

return Disposables.create {
    disposable.dispose()
}

How is standard practice to handle disposing/cancelling of publishers in a Future?

I tried simply adding:

_ = somePublisher...

But then the publisher isn't kept alive and will simply not activate at all. Should I just hook on .store(in: &cancellables) to the end of the publisher. But them, when do I cancel those cancellables? Or is there some way of returning cancellables, like in RxSwift? What am I missing?


Solution

  • The answer is, you don't. A Combine Future is like an RxSwift Single that can't be canceled once it starts.