How to continue the stream with error in Rx?

余生颓废 提交于 2019-12-08 10:04:29

问题


I am developing an Android app using Kotlin, RxJava, Retrofit. I want to send Http Request to the server.

PUT - update option of job

POST - run the job

After the first request success, then I send a second request. So I used concatMap.

val updateJob = restService.updateJob(token, job.id, options) // PUT
val runJob = restService.runJob(token, job.id) // POST

updateJob.concatMap { runJob }
    .subscribeOn(Schedulers.io())
    .observeOn(AndroidSchedulers.mainThread())
    .subscribe({ job ->
        Log.d(TAG, "runJob - success: $job")
    }, {
        Log.e(TAG, "runJob - failed: ${it.message}")
        it.printStackTrace()
    })

But I don't know in case of multiple jobs like below.

I have a job list. If one job's "update" request is failed, "run" request should not be sent. But the next job should continue. To do this, I make a code like below.

    Observable.fromIterable(jobs.toList())
    .concatMap { job ->
        val updateJob = restService.updateJob(token, job.id, job)   // HTTP PUT Request
        val runJob = restService.runJob(token, job.id)  // HTTP POST Request

        updateJob.concatMap { runJob }
    }
    .window(1)
    .subscribeOn(Schedulers.io())
    .observeOn(AndroidSchedulers.mainThread())
    .subscribe({
        it.subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe({
                Log.e(TAG, "run job - success")
            }, {
                Log.e(TAG, "run job - failed - 1: ${it.message}")
                it.printStackTrace()
            })
    }, {
        Log.e(TAG, "run job - failed - 2: ${it.message}")
        it.printStackTrace()
    })

I thought that "window" operator may be the solution. But it doesn't ... If some job is failed, the stream is over with onError(). How should I solve this problem?


回答1:


I resolve this issue using the following code.

Observable.fromIterable(jobs.toList())
    .concatMap { job ->
        val updateJob = restService.updateJob(token, job.id, job)   // HTTP PUT Request
                .onErrorResumeNext(Observable.empty<Job>()) // Solution Point
        val runJob = restService.runJob(token, job.id)  // HTTP POST Request

        updateJob.concatMap { runJob }
    }
    // .window(2)    I removed this line.
    .subscribeOn(Schedulers.io())
    .observeOn(AndroidSchedulers.mainThread())
    .subscribe({
        Log.d(TAG, "run job - success")
    }, {
        Log.e(TAG, "run job - failed - 2: ${it.message}")
        it.printStackTrace()
    })


来源:https://stackoverflow.com/questions/53439986/how-to-continue-the-stream-with-error-in-rx

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!