Guest User

Untitled

a guest
Jan 22nd, 2018
81
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.78 KB | None | 0 0
  1. import io.reactivex.Observable
  2. import io.reactivex.Single
  3. import io.reactivex.schedulers.Schedulers
  4. import junit.framework.Assert
  5. import org.junit.Test
  6. import java.util.*
  7.  
  8. class SkipExceptionTest {
  9.  
  10. private val data: Map<Int, String> = mapOf(
  11. Pair(1, "one"),
  12. Pair(2, "two"),
  13. Pair(4, "four"),
  14. Pair(5, "five")
  15. )
  16.  
  17. @Test
  18. fun canFilterOnError() {
  19. val actual = getStream(listOf(1, 2, 3, 4, 5))
  20. .subscribeOn(Schedulers.trampoline())
  21. .observeOn(Schedulers.trampoline())
  22. .test()
  23. .assertComplete()
  24. .assertNoErrors()
  25. .assertValueCount(1)
  26. .values()[0]
  27.  
  28. val expected = listOf("one", "two", "four", "five")
  29. Assert.assertEquals(expected, actual)
  30.  
  31. }
  32.  
  33. private fun getStream(list: List<Int>): Single<List<String>> {
  34. return Observable.fromIterable(list)
  35. .flatMapSingle {
  36. getValue(it)
  37. .map {
  38. Optional.of(it)
  39. }
  40. .onErrorResumeNext {
  41. when (it) {
  42. is NotFoundException -> Single.just(Optional.empty())
  43. else -> Single.error(it)
  44. }
  45. }
  46. }
  47. .filter { it.isPresent }
  48. .map { it.get() }
  49. .toList()
  50. }
  51.  
  52. private fun getValue(id: Int): Single<String> {
  53. return Single.fromCallable {
  54. data[id] ?: throw NotFoundException("data with id $id does not exist")
  55. }
  56. }
  57.  
  58. class NotFoundException(message: String) : Exception(message)
  59. }
Add Comment
Please, Sign In to add comment