Is there an operator that can filter nil
? The closest I've come is the solution mentioned here: https://github.com/ReactiveX/RxSwift/issues/209#issuecomment-150842686
Relevant excerpt:
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() }
}
}
However, after .notNil()
, E
is still optional, so subsequent chained operators still see self
as Observer<E>
where E
is optional. So I'm still needing an extra operator that does:
.map { (username: String?) -> String in
return username!
}
I must be missing something. This seems like it would be a very common need.
In RxSwift 5 it's possible using compactMap
from core library:
observable.compactMap { $0 }