Skip to content

Instantly share code, notes, and snippets.

@kakajika
Created December 13, 2018 11:10
Show Gist options
  • Save kakajika/61cd38de13d38f414378cdf32c1e8543 to your computer and use it in GitHub Desktop.
Save kakajika/61cd38de13d38f414378cdf32c1e8543 to your computer and use it in GitHub Desktop.
mapNotNull operators for Rx Observable/Single/Maybe.
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