Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handling Error RXJava Android with Kotlin

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.

like image 684
Shudy Avatar asked Sep 23 '18 17:09

Shudy


People also ask

Can I use RxJava with Kotlin?

RxJava can be used even when using the Kotlin language for app development.

What happens when an error occurs using RxJava?

RxJava Error Handling That means that after error happened stream is basically finished and no more events can come through it. If Consumer didn't handle error in Observer callback, then that error is sent to a global error handler (which in case of Android crashes the app by default).

How do you catch exceptions in Kotlin?

In Kotlin, we use try-catch block for exception handling in the program. The try block encloses the code which is responsible for throwing an exception and the catch block is used for handling the exception. This block must be written within the main or other methods.

How do you throw a mistake in Kotlin?

If you want to alert callers about possible exceptions when calling Kotlin code from Java, Swift, or Objective-C, you can use the @Throws annotation. Read more about using this annotation for Java and for Swift and Objective-C.


1 Answers

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.

like image 124
Ahmed Ashraf Avatar answered Sep 18 '22 18:09

Ahmed Ashraf