Search code examples
rx-javarx-java2rx-androidreactivex

How to limit retryWhen count


I'm using a PublishSubject in retryWhen to allow the user to retry the operation similarly to this answer. everything works fine but there's one problem - after 3 times the user clicked retry I should not allow the retry anymore and should abort the operation. is there a way to limit the retry to 3 times? I've tried publishSubject.take(3) operator but it didn't worked.


Solution

  • Operators, such as retryWhen have a secondary flow whose outcome affects the primary flow. Consequently, flow manipulation can be performed on this secondary flow as well, thus you can apply all sorts of operators to shape its outcome:

    Adapting this: https://stackoverflow.com/a/47677308/61158

    final PublishSubject<Object> retrySubject = PublishSubject.create();
    
    disposable.add(
        getData()
        .doOnError(throwable -> enableButton())
        .retryWhen(observable -> 
            observable.zipWith(retrySubject, 
                 (o, o2) -> o
            )
            .take(3)  // <------------------------ maximum 3 items from the secondary sequence
            .concatWith(Observable.error(new RetriesExhaustedException()));
         )
        .subscribeWith(/* do what you want with the result*/)
    );