使用Kotlin处理错误RXJava Android [英] Handling Error RXJava Android with Kotlin

查看:361
本文介绍了使用Kotlin处理错误RXJava Android的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好,我是RxJava和Kotlin的新手,我松了一些有关它的概念.

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

我有这样的"api":

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)

最后我打了电话:

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.

我尝试添加:.doOnError { error -> Log.d("MainClass",error.message) },但仍然显示相同的错误消息.

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

推荐答案

您可以将另一个lambda传递给subscribe,以处理特定流的错误,如下所示:

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 } )
    )
}

PS:doOnError和其他副作用运算符不会无论如何影响流,他们只是预期副作用操作(例如日志记录)发出的值.

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.

这篇关于使用Kotlin处理错误RXJava Android的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆