Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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()
}
like image 679
Dj S Avatar asked Dec 06 '25 05:12

Dj S


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.

like image 75
donnywals Avatar answered Dec 09 '25 03:12

donnywals



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!