Created
May 6, 2016 00:04
-
-
Save alskipp/e71f014c8f8a9aa12b8d8f8053b67d72 to your computer and use it in GitHub Desktop.
How to ignore `nil` values using RxSwift without using❗️
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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 | |
*/ |
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
flatMap { Observable.from( optional: $0.optional ) }