如何使用 Publishers.CombineLatest 获得 1 个发布者

how to use Publishers.CombineLatest to get 1 publisher

我正在尝试使用 2 个发布者并让它们流式传输到从两个值映射的 1 个发布者。

我的代码是:

class ViewModel {

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

    lazy var isEmailValid = email.map { self.validateEmail(email: [=11=]) }

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

    lazy var isPasswordCorrect = password.map {
        self.validatePassword(password: [=11=])
    }

    let canLogin: CurrentValueSubject<Bool, Never>

    private func validateEmail(email: String) -> Bool {
        return email == "1234@gmail.com"
    }

    private func validatePassword(password: String) -> Bool {
        return password == "1234"
    }


    init() {
    
        canLogin = Publishers
            .CombineLatest(isEmailValid, isPasswordCorrect)
            .map { [=11=] &&  } 

    }
}

然后在初始化中我得到这个错误:

    //error: Cannot assign value of type 
'Publishers.Map<Publishers.CombineLatest<Publishers.Map<CurrentValueSubject<String, Never>, 
Bool>, Publishers.Map<CurrentValueSubject<String, Never>, Bool>>, Bool>' to type 'CurrentValueSubject<Bool, Never>'

我是新手,所以我觉得有点困惑。 我应该如何从上面的代码中将 2 个发布者 isEmailValid 和 isPasswordCorrect 组合成 1 个发布者,即 CurrentValueSubject?

一个CurrentValueSubject是:

A subject that wraps a single value and publishes a new element whenever the value changes.

你的canLogin肯定不是CurrentValueSubject。它是将其他两个发布者与 CombineLatest 运算符合并,然后将合并后的发布者映射到另一个发布者的结果。

在Swift类型系统的语言中,这种发布者被称为:

Publishers.Map<Publishers.CombineLatest<Publishers.Map<CurrentValueSubject<String, Never>, Bool>, Publishers.Map<CurrentValueSubject<String, Never>, Bool>>, Bool>

显然,没有人会用这样的类型声明一个 属性,所以我们使用 eraseToAnyPublisher 来让自己得到一个 AnyPublisher,表示我们实际上并不关心它是什么类型的发布者。

let canLogin: AnyPublisher<Bool, Never>

...

canLogin = Publishers
        .CombineLatest(isEmailValid, isPasswordCorrect)
        .map { [=11=] &&  } 
        .eraseToAnyPublisher()

您完全错误地声明了 canLogin 的类型。

它需要是一个 AnyPublisher,您只需在 map 上调用 eraseToAnyPublisher 即可获得。

lazy var canLogin: AnyPublisher<Bool, Never> = isEmailValid.combineLatest(isPasswordCorrect).map { [=10=] &&  }.eraseToAnyPublisher()