首页 > 解决方案 > Combine two AnyPublisher in Combine

问题描述

I have a two tests for a username, I want two so I can have different messages for the length of the username and one for the validity of a username.

Fine so far, but I want to combine them to make sure that I can enable my register UIButton

@Published var username: String = ""

var validLengthUsername: AnyPublisher<Bool, Never> {
    return $username.debounce(for: 0.2, scheduler: RunLoop.main)
        .removeDuplicates()
        .map{$0.count > 6 ? true : false}
        .eraseToAnyPublisher()
}

var formattedUserName: AnyPublisher<Bool, Never> {
    return $username
        .removeDuplicates()
        .map{$0.isValidEmail() ? true : false}
        .eraseToAnyPublisher()
}

I'm trying to map them -but this gives me an array of AnyPublisher. This isn't what I want - I want to combine validLengthUsername && formattedUserName - I tried just that but I can't simply AND the two AnyPublisher.

标签: swiftcombine

解决方案


You can use zip to create a Publisher, which will emit a value once both publishers have emitted a new value and use the AND operator on the elements of the zipped publisher.

var fullValidation: AnyPublisher<Bool, Never> {
    validLengthUsername
        .zip(formattedUserName)
        .map { $0 && $1 }
        .eraseToAnyPublisher()
}

推荐阅读