Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 594
solidcell Avatar asked Nov 27 '22 01:11

solidcell


2 Answers

In RxSwift 5 it's possible using compactMap from core library:

observable.compactMap { $0 }
like image 62
Lion Avatar answered Dec 22 '22 04:12

Lion


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

like image 31
Pham Hoan Avatar answered Dec 22 '22 05:12

Pham Hoan