StuckOverFlow
StuckOverFlow

Reputation: 891

Combine: how to early exit with error from a guard precondition

I want to create a method authenticate which, using Combine, allows the user to login with my API.

I am trying to add now a precondition, so that if the provided username is empty, my method does not touch the network. I want to make an early exist at this point, providing an error back to the Subscriber.

Please find below an snippet of my code. How could I return an error from the early exist in line 4?

func authenticate(username: String, password: String) -> AnyPublisher<User, Error> {

        guard !username.isEmpty else {
            // How to return an error to the subscribers from here?????
            return
        }

        let parameters: [String: Any] = [
            "username": username,
            "password": password
        ]

        var request = URLRequest(endpoint: Endpoint.login)
        request.addValue("application/json", forHTTPHeaderField: "Content-Type")
        request.httpBody = try? JSONSerialization.data(withJSONObject: parameters, options: [])

        return URLSession.shared.dataTaskPublisher(for: request)
            .map { $0.data }
            .decode(type: AuthenticationResult.self, decoder: JSONDecoder())
            .map { $0.user }
            .receive(on: RunLoop.main)
            .eraseToAnyPublisher()
    }

Upvotes: 1

Views: 598

Answers (1)

Alex
Alex

Reputation: 8991

You can use Fail, which is a type of Publisher:

return Fail(error: MyError.missingUsername).eraseToAnyPublisher()

Upvotes: 7

Related Questions