Created
December 13, 2018 11:10
-
-
Save kakajika/61cd38de13d38f414378cdf32c1e8543 to your computer and use it in GitHub Desktop.
mapNotNull operators for Rx Observable/Single/Maybe.
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
fun <T, R> Observable<T>.mapNotNull(mapper: (T) -> R?): Observable<R> { | |
return lift { observer -> | |
object: Observer<T> { | |
override fun onNext(t: T) { | |
mapper(t)?.let { observer.onNext(it) } | |
} | |
override fun onComplete() { | |
observer.onComplete() | |
} | |
override fun onError(e: Throwable) { | |
observer.onError(e) | |
} | |
override fun onSubscribe(d: Disposable) { | |
observer.onSubscribe(d) | |
} | |
} | |
} | |
} | |
fun <T, R> Single<T>.mapNotNull(mapper: (T) -> R?): Maybe<R> { | |
return toMaybe().mapNotNull(mapper) | |
} | |
fun <T, R> Maybe<T>.mapNotNull(mapper: (T) -> R?): Maybe<R> { | |
return lift { observer -> | |
object: MaybeObserver<T> { | |
override fun onSuccess(t: T) { | |
mapper(t)?.let { observer.onSuccess(it) } | |
?: run { observer.onComplete() } | |
} | |
override fun onComplete() { | |
observer.onComplete() | |
} | |
override fun onError(e: Throwable) { | |
observer.onError(e) | |
} | |
override fun onSubscribe(d: Disposable) { | |
observer.onSubscribe(d) | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment