Handling Error RXJava Android with Kotlin

假装没事ソ 提交于 2019-12-10 04:29:04

问题


Hi I'm new with RxJava and Kotlin and I loose some concepts about it.

I have "api" like this:

interface VehiclesService {
    @GET("/vehicles/")
    fun getVehicles(): Single<List<Vehicle>>
}

Then I create the retrofit client, etc.. like this:

var retrofit = RetrofitClient().getInstance()
vehiclesAPI = retrofit!!.create(VehiclesService ::class.java)

finally I do the call:

private fun fetchData() {
        compositeDisposable.add(vehiclesAPI .getVehicles()
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe { vehicles -> displayData(vehicles) }
        )
    }

And here is where I have the error when I try to launch:

The exception was not handled due to missing onError handler in the subscribe() method call

I know that the error is quite explicit. So I know what is missing, but what I don't know is HOW to handle this error.

I tried adding : .doOnError { error -> Log.d("MainClass",error.message) } but still telling same error message.


回答1:


You can pass another lambda to subscribe to handle the errors for a specific stream like this:

    private fun fetchData() {
    compositeDisposable.add(vehiclesAPI .getVehicles()
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe( { vehicles -> displayData(vehicles) }, { throwable -> //handle error } )
    )
}

P.S: doOnError and other Side Effect operators, will not affect the stream in anyway, they just anticipate the values emitted for side-effect operations like logging for example.



来源:https://stackoverflow.com/questions/52468708/handling-error-rxjava-android-with-kotlin

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