Retry network calls in RxJava

2019-09-16 09:32发布

问题:

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.