是否有可以过滤nil
的运算符?我最接近的是这里提到的解决方案:https://github.com/ReactiveX/RxSwift/issues/209#issuecomment-150842686
相关摘录:
public protocol OptionalType {
func hasValue() -> Bool
}
extension Optional: OptionalType {
public func hasValue() -> Bool {
return (self != nil)
}
}
public extension ObservableType where E: OptionalType {
@warn_unused_result(message="http://git.io/rxs.uo")
public func notNil() -> Observable<E> {
return self.filter { $0.hasValue() }
}
}
但是,在.notNil()
之后,E
仍然是可选的,因此后续的链式运算符仍会将self
视为Observer<E>
,其中E
是可选的。所以我仍然需要一个额外的运算符:
.map { (username: String?) -> String in
return username!
}
我一定错过了什么。这似乎是一个非常普遍的需求。
答案 0 :(得分:1)
https://github.com/RxSwiftCommunity/RxSwift-Ext点检unwrap
:)
或https://github.com/RxSwiftCommunity/RxOptional
目前,您应该根据个人需要使用RxOptional
但是,RxSwift-Ext
将在未来2-3个月内呈指数级增长:)
RxSwift
的闲谈中与对方聊天:))
答案 1 :(得分:0)
在RxSwift 5中,可以使用核心库中的compactMap
:
observable.compactMap { $0 }
答案 2 :(得分:0)
nil
值,请使用 RxSwiftExt.unwrap()nil
值,只需执行以下操作:observableContainingNils.filter { $0 == .none }