Eyzuky
Eyzuky

Reputation: 1945

Map an AnyPublisher to another AnyPublisher

I have this code:

class ViewModel {

    let email = CurrentValueSubject<String, Never>("")

    private var isEmailValid: AnyPublisher<Bool, Never>?

    var emailColor: AnyPublisher<UIColor, Never>?


    private func validateEmail(email: String) -> Bool { return email == "[email protected]" }
    private func emailColor(isValid: Bool) -> UIColor { return isValid ? UIColor.black : 
UIColor.red }

    public func setupPublishers() {
        isEmailValid = email
        .map { self.validateEmail(email: $0) }
        .eraseToAnyPublisher()

        emailColor = email
        .map { self.emailColor(isValid: self.validateEmail(email: $0)) }
        .eraseToAnyPublisher()
    }
}

In the function setupPublishers, I create isEmailValid as a map from the CurrentValueSubject 'email'. I wish to map it directly from 'isEmailValid', but if I do this:

        emailColor = isEmailValid
        .map { self.emailColor(isValid: $0) }
        .eraseToAnyPublisher()

I get this error:

Cannot convert value of type 'AnyPublisher<Bool, Never>' to expected argument type 'Bool'
Value of type 'UIColor?' has no member 'eraseToAnyPublisher'

Which obviously indicates that mapping from the publisher gives me the actual value instead of another publisher. So how could I achieve this task?

Upvotes: 0

Views: 2856

Answers (1)

David Pasztor
David Pasztor

Reputation: 54775

That error message doesn't make any sense, the real error was that isEmailValid is Optional, so you need to use optional chaining on it to be able to call map.

emailColor = isEmailValid?
        .map { self.emailColor(isValid: $0) }
        .eraseToAnyPublisher()

Upvotes: 1

Related Questions