Group Group Group Group Group Group Group Group Group

Cancelling a Future

I am enjoying the Combine book so far. I work at a company where we develop SDKs. In our swift api, I am looking to use Future as a return type for async functions, it seems like a perfect fit.

However, I need to be able to cancel the code that is running in the future. In the book, for example, we wrote an async method like so:


    static func save(_ image: UIImage) -> Future<String, PhotoWriter.Error> {
        return Future { resolve in
            do {
                try PHPhotoLibrary.shared().performChangesAndWait {
                    let request = PHAssetChangeRequest.creationRequestForAsset(from: image)
                    guard let savedAssetID = request.placeholderForCreatedAsset?.localIdentifier else {
                        return resolve(.failure(.couldNotSavePhoto))
                    }
                    resolve(.success(savedAssetID))
                }
            } catch {
                resolve(.failure(.generic(error)))
            }
        }
    }

But what if the code that I’m running the future is “cancellable”, meaning it might be a few network requests and if the user cancels the subscription, or the subscription is dealloc’d, how can I cancel the network requests, or the async code that I have running?

I can’t figure out a way to be notified that the subscription to the future was cancelled.

Thanks

Reading further, it looks like you cancel with the handleEvents function:

...
.handleEvents(receiveCancel: {
  self.dismiss(animated: true)
})
.eraseToAnyPublisher()