Handling Error RXJava Android with Kotlin

2019-05-13 18:02发布

问题:

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.