Code:
import Combine
func login() -> Future<Token, Error> { ... }
func updateImage() -> Future<Status, Never> { ... }
func getProfile() -> Future<Profile, Error> { ... }
I need to perform something like this (sequential actions):
login()
.catch { error in
... //handle error
}
.flatMap { token in
...//handle login results
return updateImage()
}
.catch { _ in
... //skip error
}
.flatMap {
... //handle updateImage results
return getProfile()
}
.sink(...) //handle getProfile results and errors
The problem is Combine has misleading types inside flatMap and catch.
Tried to return Empty inside catch blocks:
return Empty<String, CustomError>(completeImmediately: true)
.eraseToAnyPublisher()
But I don't understand if it stops producing errors in sink section. And is it a correct approach for my task in general?
If you want to chain multiple of these independent
Futures, and handle errors in each step, you can follow the pattern:Each of these is a publisher that either publishes one
(), or no values at all. Then you can chain multiple of these together withflatMap:To help the compiler figure out the types more quickly, or even at all, you should add explicit return types and/or
eraseToAnyPublisher()where appropriate.As Dávid Pásztor's answer said, if
loginand so on areasyncmethods instead, this chaining is built directly into the language. You can write a "chain" in the same way as you write sequential statements.