简体   繁体   English

Android RxJava2 API错误处理

[英]Android RxJava2 API error handling

I am new to RxJava . 我是RxJava

We are using Retrofit2 + RxJava2 for calling APIs. 我们正在使用Retrofit2 + RxJava2来调用API。

I have the following scenario - 我有以下情况-

1. Call Cart API 1.调用购物车API
2. If Cart API fails I need to call Login API 2.如果购物车API失败,我需要调用登录API
3. On Success of Login API I need to call Cart API again 3.登录API成功后,我需要再次调用Cart API

Call {API} -> {API} fails -> call Login API -> on success of Login API -> call {API}. 调用{API}-> {API}失败->调用Login API->成功登录API->调用{API}。

Like this way, if any API fails I need to call Login API and then call the failed API. 这样,如果任何API失败,我需要调用Login API,然后再调用失败的API。

Whats the best way handle this. 什么是处理此问题的最佳方法。

You could do something like this: 您可以执行以下操作:

api.processCart()
    .retryWhen(errors -> errors
                           .filter(it -> it == LOGIN_ERROR)
                           .flatMap(api.login())

Beware that this could create a never-ending loop if you are not careful. 请注意,如果不小心,这可能会造成永无止境的循环。 You can insert any logic you want in the retryWhen handler. 您可以在retryWhen处理程序中插入所需的任何逻辑。 As in the example, you could check the type of the error and decide if you need to relogin or do something else. 如示例中所示,您可以检查错误的类型并确定是否需要重新登录或执行其他操作。

But if you need to do this for every api call, it'd be worth taking a look at Fred's comment. 但是,如果您需要为每个api调用执行此操作,则值得看看Fred的评论。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM