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

2024-01-06

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

我的代码是:

class ViewModel {

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

    lazy var isEmailValid = email.map { self.validateEmail(email: $0) }

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

    lazy var isPasswordCorrect = password.map {
        self.validatePassword(password: $0)
    }

    let canLogin: CurrentValueSubject<Bool, Never>

    private func validateEmail(email: String) -> Bool {
        return email == "[email protected] /cdn-cgi/l/email-protection"
    }

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


    init() {
    
        canLogin = Publishers
            .CombineLatest(isEmailValid, isPasswordCorrect)
            .map { $0 && $1 } 

    }
}

然后在 init 中我得到这个错误:

    //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 发布者?


A CurrentValueSubject https://developer.apple.com/documentation/combine/currentvaluesubject is:

包装单个值并在值发生变化时发布新元素的主题。

Your 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 { $0 && $1 } 
        .eraseToAnyPublisher()
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何使用 Publishers.CombineLatest 获取 1 个发布者 的相关文章

随机推荐