Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 960
Ekra Avatar asked Jan 25 '23 22:01

Ekra


1 Answers

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))
)
like image 88
Sweeper Avatar answered Jan 27 '23 12:01

Sweeper