在 RxJava 中重试网络调用 [英] Retry network calls in RxJava

查看:62
本文介绍了在 RxJava 中重试网络调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Android 中 rxJava 出现网络错误时如何重试网络调用.

How to make retry network calls when network errors appear with rxJava in Android.

这是我的 rxJave 代码:

Here is my rxJave code:

RxTextView.textChanges(searchInput)
            .debounce(500, TimeUnit.MILLISECONDS)
            .map(CharSequence::toString)
            .filter(s -> !s.isEmpty())
            .subscribeOn(AndroidSchedulers.mainThread())
            .observeOn(Schedulers.io())
            .switchMap(query -> getTypedPlaces(query))
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(results -> showResult(results));

效果很好,但我需要在连接中断时重试网络请求.

It works very well but I need to retry network request when connection was down.

推荐答案

制作 PublishSubject 并添加 retryWhen(subject).

然后监听连接的变化,当网络可用时调用 subject.onNext(null),如果你的 rx-chain 停止,它将重试.

Then listen for changes to connectivity and when the network becomes available call subject.onNext(null) and if your rx-chain is stalling on that it will retry.

.switchMap(query -> getTypedPlaces(query).retryWhen(subject))

其他注意事项...

.subscribeOn(AndroidSchedulers.mainThread()) 是多余的,因为 TextView 上的事件源自 mainThread.

.subscribeOn(AndroidSchedulers.mainThread()) is superfluous as the events on the TextView originate from the mainThread.

.observeOn(Schedulers.io()) 可能不是必需的,或者您可以专门在 debounce 中设置调度程序.

.observeOn(Schedulers.io()) may not be necessary or you could just set the scheduler specifically in debounce.

这篇关于在 RxJava 中重试网络调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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