Search code examples
swiftcombinepublisher

Swift Combine return Publisher from func


I want to return the publisher for a function if there is error in input params for it but its giving some compilation error.

Below is the function for the same.

func fetchList(input: String) -> AnyPublisher<List, Error> {
    guard let url = URL(string: input)  else {            
        return AnyPublisher(URLError(.cannotParseResponse))
    }
    //some call for to get the List which returns publisher
}

Error

Cannot invoke initializer for type 'AnyPublisher<_, _>' with an argument list of type '(URLError)'

Summary

How to create our publisher to return the error?

Thanks for any hint in the right direction.


Solution

  • AnyPublisher requires a Publisher as its initialiser argument, whereas you are giving it URLError. You probably mean to say "I want a publisher that publishes an error immediately". To do that, you use the Fail publisher:

    return AnyPublisher(
        Fail<List, Error>(error: URLError(.cannotParseResponse))
    )