2

I have been playing with Apple's Combine framework, There I found couple of operators map() & tryMap() or allSatisfy() & tryAllSatisfy

many operators in Combine follows this pattern, I wonder what does this meant for.

I gone through with many operator, most of them have prefixed try. If some one can let me know in most plain manner, that would really helpful.

Thanks

Dávid Pásztor
  • 51,403
  • 9
  • 85
  • 116
Nasir
  • 1,617
  • 2
  • 19
  • 34

2 Answers2

8

The try variants give the accompanying function the opportunity to throw an error. If the function does throw an error, that error is passed downstream (and the entire pipeline is completed, failing in good order).

So, for example, map takes a function, but you cannot say throw in that function. If you would like to be able to say throw, use tryMap instead. And so on.

matt
  • 515,959
  • 87
  • 875
  • 1,141
3

The map operator cannot introduce failures. If the upstream Failure type is Never, then after map, the Failure type is still Never. If the upstream Failure type is DecodingError, then after map, the Failure type is still DecodingError:

let up0: AnyPublisher<Int, Never> = ...

let down0: AnyPublisher<String, Never> = up0
//                              ^^^^^ still Never, like up0
    .map { String($0) }
    .eraseToAnyPublisher()

let up1: AnyPublisher<Int, DecodingError> = ...

let down1: AnyPublisher<String, DecodingError> = up1
//                              ^^^^^^^^^^^^^ still DecodingError, like up1
    .map { String($0) }
    .eraseToAnyPublisher()

The tryMap operator ends the stream with a failure completion if the closure throws an error. A throwing closure can throw any Error. The error type is not restricted. So tryMap always changes the Failure type to Error:

let up2: AnyPublisher<Int, Never> = ...

let down2: AnyPublisher<String, Error> = up2
//                              ^^^^^ changed from Never to Error
    .tryMap { String($0) }
    .eraseToAnyPublisher()

let up3: AnyPublisher<Int, DecodingError> = ...

let down3: AnyPublisher<String, Error> = up3
//                              ^^^^^ changed from DecodingError to Error
    .tryMap { String($0) }
    .eraseToAnyPublisher()
rob mayoff
  • 375,296
  • 67
  • 796
  • 848
  • 2
    I definitely agree with this! In my https://www.apeth.com/UnderstandingCombine/operators/operatorsTransformersBlockers/operatorsmap.html I particularly note the use of tryMap to change the error type downstream. – matt Oct 21 '20 at 20:56