Is there a function in Swift + Combine similar to PromiseKit's "ensure"?

Viewed 713

I would like to be able to run a block of code no matter what the outcome of the publishing chain is. Is there something similar in Combine + Swift?

Something like this:

func doSomeLongRunningTask() -> AnyPublisher<Void, Error> {
  return Future<Void, Error> {
    showSpinner()
  }.tryMap {
    longRunningTaskCanThrowError()
  }.ensure {
    hideSpinner()
  }.eraseToAnyPublisher()
}
1 Answers

The closest would be handleEvents:

func doSomeLongRunningTask() -> AnyPublisher<Void, Error> {
  return Future<Void, Error> {
    showSpinner()
  }.tryMap {
    longRunningTaskCanThrowError()
  }.handleEvents(receiveCompletion: { _ in
    hideSpinner()
  }).eraseToAnyPublisher()
}

The code in the receiveCompletion code will run when the publisher completes either successfully, or with an error.

Related