Ignoring/filtering nil
Asked Answered
H

3

5

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.

Hereinbefore answered 11/4, 2016 at 19:36 Comment(0)
T
3

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

Tomi answered 12/4, 2016 at 1:11 Comment(0)
G
39

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

observable.compactMap { $0 }
Goldstein answered 27/6, 2019 at 18:44 Comment(0)
T
3

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

Tomi answered 12/4, 2016 at 1:11 Comment(0)
H
0
  • To filter out the nil values, use RxSwiftExt.unwrap()
  • And to filter only the nil values, simply do this:
observableContainingNils.filter { $0 == .none }
Haileyhailfellowwellmet answered 13/1, 2021 at 9:54 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.