如何返回可观察的< string>基于可观察的< bool> rxswift
我是RXSWIFT的新手。
有什么方法我可以创建一个函数,该函数将根据下面的两个函数的条件返回可观察的函数,
func isValidPassword(_ str: PublishSubject<String>) -> Observable<Bool> {
return str.asObservable().map {
validator.isValidPasswordRegex($0) && $0.count >= 8
}
}
func isNotEmpty(_ str: PublishSubject<String>) -> Observable<Bool> {
return str.asObservable().map {
$0.count != 0
}
}
这只是我要实现的目标的一个示例,希望您能有这个想法。
func someFunc(_ str:PublishSubject<String>) -> Observable<String> {
if !isValidPassword(str){
return "Not a valid password" //should return as an observable string
}
if isNotEmpty(str){
return "String is not empty" //should return as an observable string
}
}
I'm quite new to RxSwift.
Is there any way I can create a function that will return Observable based on the conditions of two functions below
func isValidPassword(_ str: PublishSubject<String>) -> Observable<Bool> {
return str.asObservable().map {
validator.isValidPasswordRegex($0) && $0.count >= 8
}
}
func isNotEmpty(_ str: PublishSubject<String>) -> Observable<Bool> {
return str.asObservable().map {
$0.count != 0
}
}
This code below is just an example of what I'm trying to achieve, hoped you got the idea.
func someFunc(_ str:PublishSubject<String>) -> Observable<String> {
if !isValidPassword(str){
return "Not a valid password" //should return as an observable string
}
if isNotEmpty(str){
return "String is not empty" //should return as an observable string
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我不确定您在这里要实现的目标,但我认为您应该使用
filter
运算符,而不是map
。这样,您就不会更改可观察的起始类型,而是删除不尊重您条件的元素。I'm not sure about what you want to achieve here but I think you should use
filter
operator and notmap
. In this way you don't change the type of the starting observable but you remove elements that don't respect your conditions.让我向您介绍
ZIP
...它允许您组合多个可观察到的物品。请注意,我更新了您现有功能的类型签名:
通过这样的主题是灾难的秘诀。
更新
我认为,如果您实现这样的实现,则代码会更好:
更易于测试要容易得多这边走。
Let me introduce you to
zip
... It allows you to combine multiple Observables.Note that I updated the type signatures of your existing functions:
Passing Subjects around like that is a recipe for disaster.
UPDATE
I think the code would be better if you implemented like this though:
It's much easier to test this way.