Search code examples
iosswiftfrpcombine

Set a given Publishers Failure type to Never in Combine


Is there a way to transform a given AnyPublisher<AnyType, SomeError> to AnyPublisher<AnyType, Never>?


Solution

  • A publisher with Never as error type mean that it can't throw error at all. It will always deliver a value.

    To obtain a publisher that can never throw errors you have 2 solutions:

    1/ Catch all possible errors:

    let publisher: AnyPublisher<AnyType, SomeError> = //...
    
    publisher.catch { error in
      // handle the error here. The `catch` operator requires to
      // return a "fallback value" as a publisher
      return Just(/* ... */) // as an example
    }
    

    2/ If you are sure that there no errors can be thrown by the publisher, you can use .assertNoFailure(), that will convert your publisher. Note that is an error pass through the .assertNoFailure(), your app will crash immediately.