Skip to content

Instantly share code, notes, and snippets.

@alskipp
Created May 6, 2016 00:04
Show Gist options
  • Star 16 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alskipp/e71f014c8f8a9aa12b8d8f8053b67d72 to your computer and use it in GitHub Desktop.
Save alskipp/e71f014c8f8a9aa12b8d8f8053b67d72 to your computer and use it in GitHub Desktop.
How to ignore `nil` values using RxSwift without using❗️
// Create an `Observable` of Optional<Int>
let values: Observable<Int?> = [1, 2, .None, 3, .None, 4, 5].toObservable()
// Method 1: using a free function
// Requires passing the function to `flatMap`
func ignoreNil<A>(x: A?) -> Observable<A> {
return x.map { Observable.just($0) } ?? Observable.empty()
}
values
.flatMap(ignoreNil)
.subscribeNext { print($0) }
/*
1
2
3
4
5
*/
// Method 2: extending Observable
// More convenient to use, but more painful to implement!
public protocol OptionalType {
associatedtype Wrapped
var optional: Wrapped? { get }
}
extension Optional: OptionalType {
public var optional: Wrapped? { return self }
}
// Unfortunately the extra type annotations are required, otherwise the compiler gives an incomprehensible error.
extension Observable where Element: OptionalType {
func ignoreNil() -> Observable<Element.Wrapped> {
return flatMap { value in
value.optional.map { Observable<Element.Wrapped>.just($0) } ?? Observable<Element.Wrapped>.empty()
}
}
}
values
.ignoreNil()
.subscribeNext { print($0) }
/*
1
2
3
4
5
*/
@desmondmc
Copy link

That's a huge help. Thanks a lot.

@sofacoder
Copy link

Those that come along here while looking for a solution may also have a look at RxOptional

@sssbohdan
Copy link

Observable<Int?>.from([1, 2, 3, nil, 5, nil, 7]).filter { $0 != nil }.map { $0! }
Why not like this?

@yngty
Copy link

yngty commented Jul 26, 2018

flatMap { Observable.from( optional: $0.optional ) }

@michaelavila
Copy link

fwiw, I like:

flatMap(Observable.from(optional:))

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment