solidcell solidcell - 5 months ago 13
Swift Question

Ignoring/filtering nil

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.

Answer

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 :)

Comments