问题
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