如何处理Android中的rxjava链中的错误?

时间:2019-06-19 04:29:48

标签: android rx-java rx-kotlin rx-kotlin2

我有一个项目列表,例如整数列表,如果任何整数为null,我需要消耗该错误并继续下一个项目

例如

Observable.fromIterable(listOf(1, 2, 3, null, 5))
                .map {
                    doSomeProcess(it)
                }
                .onErrorReturnItem(-1)
                .subscribeBy(
                        onNext = {
                           print(it)
                        },
                        onError = {

                        },
                        onComplete = {

                        })

我期望这样的输出

1
2
3
-1
5

但是我的问题是在-1之后,没有继续进行项目5,它在那里停止了,有人可以帮我解决这个问题吗?

1 个答案:

答案 0 :(得分:1)

在Rx中,onError是终止事件。因此,如果您不想中断数据流,而只是处理错误并继续接收其他数据,则可以使用Notification

 Observable.fromIterable(listOf(1, 2, 3, null, 5))
            .map {
                doSomeProcess(it)
            }
            .subscribeBy(
                onNext = {
                    when {
                        it.isOnNext -> {
                            val result = it.value
                            if(result == -1){
                                //handle error here
                            }
                        }
                        //it.isOnComplete -> {
                        //}
                        //it.isOnError -> {
                        //}
                    }
                }
            )


 private fun doSomeProcess(i: Int?): Notification<Int> =
    if (i == null)
        //Notification.createOnError(IllegalArgumentException())
        Notification.createOnNext(-1)
    else
        Notification.createOnNext(i)