Skip to content

Instantly share code, notes, and snippets.

@randallmitchell
Last active January 12, 2018 17:43
Show Gist options
  • Save randallmitchell/b0e26e23383d299f43a935309d1f9396 to your computer and use it in GitHub Desktop.
Save randallmitchell/b0e26e23383d299f43a935309d1f9396 to your computer and use it in GitHub Desktop.
RxJava Filter on Error with Kotlin
import io.reactivex.Observable
import io.reactivex.Single
import io.reactivex.schedulers.Schedulers
import junit.framework.Assert
import org.junit.Test
import java.util.*
class SkipExceptionTest {
private val data: Map<Int, String> = mapOf(
Pair(1, "one"),
Pair(2, "two"),
Pair(4, "four"),
Pair(5, "five")
)
@Test
fun canFilterOnError() {
val actual = getStream(listOf(1, 2, 3, 4, 5))
.subscribeOn(Schedulers.trampoline())
.observeOn(Schedulers.trampoline())
.test()
.assertComplete()
.assertNoErrors()
.assertValueCount(1)
.values()[0]
val expected = listOf("one", "two", "four", "five")
Assert.assertEquals(expected, actual)
}
private fun getStream(list: List<Int>): Single<List<String>> {
return Observable.fromIterable(list)
.flatMapSingle {
getValue(it)
.map {
Optional.of(it)
}
.onErrorResumeNext {
when (it) {
is NotFoundException -> Single.just(Optional.empty())
else -> Single.error(it)
}
}
}
.filter { it.isPresent }
.map { it.get() }
.toList()
}
private fun getValue(id: Int): Single<String> {
return Single.fromCallable {
data[id] ?: throw NotFoundException("data with id $id does not exist")
}
}
class NotFoundException(message: String) : Exception(message)
}
@randallmitchell
Copy link
Author

The first version is broken. Results in test output:

junit.framework.AssertionFailedError: Expected :[one, two, four, five] Actual :[one, two]

@randallmitchell
Copy link
Author

Latest version passes.

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