swift - 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
.
解决方案
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()
}
推荐阅读
- java - 按下 AlertDialog 的肯定按钮时是否刷新 RecyclerView
- javascript - 使用 javascript 突出显示 HTML 语法错误
- angular - 如果在父组件和子组件中设置 ChangeDetectionStrategy OnPush 将不起作用
- android - 将arraylist从一个片段解析到android中的另一个片段
- c - Linux 操作系统中的 main() 计数器
- php - 在 Laravel 中启动 php.exe 时出现错误 0x2
- html - 如何进入内部 Maybe monad 从纯脚本中的 html 按钮中提取类名?
- html - 自动调整 div 边距顶部动态
- python - 如何使用python获取thingspeak通道的field1值
- typo3-8.x - TYPO3 类型为 xxx\\yyy\\Domain\\Model\\User 的对象,身份为 \"1\" 未找到。"