Retry network calls in RxJava

久未见 提交于 2019-12-25 16:45:09

问题


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

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.


回答1:


Make a PublishSubject and add retryWhen(subject).

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

other notes...

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

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



来源:https://stackoverflow.com/questions/39677693/retry-network-calls-in-rxjava

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!