How to retry a consumed Observable?

2019-06-07 10:42发布

I am trying to re-execute a defined observable that failed. Using Retrofit2 and RxJava2 together i want to retry a specific request with its subscription and behavior when clicking a button. is that possible?

service.excecuteLoginService(url,
            tokenModel,
            RetrofitManager.apiKey)
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribeWith(....)

1条回答
一纸荒年 Trace。
2楼-- · 2019-06-07 11:37

An option is to create Publisher, which emission is controlled by your button.

final PublishSubject<Object> retrySubject = PublishSubject.create();


service.excecuteLoginService(url,
            tokenModel,
            RetrofitManager.apiKey)
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .doOnError(throwable -> showButton())
            .retryWhen(observable -> observable.zipWith(retrySubject, (o, o2) -> o))
            .subscribeWith(result -> {}, error -> {});

Your button will just emit an item from the Subject:

retrySubject.onNext(EMPTY);
查看更多
登录 后发表回答