Using Just with flatMap produce Failure mismatch. Combine

There is special operator setFailureType(to:). You can override failure type to whatever error type you need.

func request(request: URLRequest) -> AnyPublisher<Data, Error> {
    return Just(request)
        .setFailureType(to: Error.self)
        .flatMap { request in
            RequestManager.request(request) // returns AnyPublisher<Data, Error>
    }
    .eraseToAnyPublisher()
}

https://developer.apple.com/documentation/combine/just/3343941-setfailuretype


If you call .mapError() on the Just output, it will change the type to include Error, but that closure will never be called (so I wouldn’t worry) — this is what I would do unless someone has a better idea.

Normally, the Self.Error == P.Error on flatMap makes sense, as you can’t just ignore errors coming from Self. But, when Self.Error is Never, you can ignore them and produce your own errors.

Tags:

Swift

Combine