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 }
checkout unwrap
at https://github.com/RxSwiftCommunity/RxSwift-Ext :)
or https://github.com/RxSwiftCommunity/RxOptional
For now, you should use RxOptional
for your personal needs
However, RxSwift-Ext
will be growth exponentially in next 2-3 months :)
P/S: these guys (i'm talking about owners of these repos) chat with each others daily on RxSwift
's slack :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With