Rakesh
Rakesh

Reputation: 4334

RxJava : Retrying a subscriber using retryWhen()

I am consuming a REST api using Vertx RxJava subscriber. I want to retry a request when there is a specific error, below is my code. When I run this, the retry keeps happening infinitely, I'd rather have it retry just thrice.

I am new to RxJava and still getting the hang of doing things in Rx way. Can someone tell if I am missing something? Thanks!

responseSingle.map(response -> {
            //do some stuff
            return responseBody;

        }).retryWhen(errors -> {
                    errors.flatMap(error -> {
                        log.info("==================== caught error ==================== ");
                        // For IOExceptions, we  retry
                        if (error instanceof MySpecificException) {
                            log.info("==================== retrying request ==================== ");
                            return Observable.just(null);
                        }

                        // For anything else, don't retry
                        return errors;
                    });
                    return errors;
                }
        ).onErrorReturn(t -> {
            //do some stuff
            return responseBody;
        });

Upvotes: 1

Views: 1503

Answers (2)

Praveena
Praveena

Reputation: 6980

You don't have to use retryWhen and retry is good enough.

responseSingle.map(response -> {
        //do some stuff
        return responseBody;

    })
    .retry((attempts,error) -> attempts<3 && error instanceof MySpecificException)  
    .onErrorReturn(t -> {
        //do some stuff
        return responseBody;
    });

It will retry if expression inside retry returns true

Upvotes: 1

Niraj Chauhan
Niraj Chauhan

Reputation: 7900

Just add .retry(count), not tested but it should work.

responseSingle.map(response -> {
            //do some stuff
            return responseBody;

        })
                .retry(3) // count of retries
                .retryWhen(errors -> {
                    errors.flatMap(error -> {
                        log.info("==================== caught error ==================== ");
                        // For IOExceptions, we  retry
                        if (error instanceof MySpecificException) {
                            log.info("==================== retrying request ==================== ");
                            return Observable.just(null);
                        }

                        // For anything else, don't retry
                        return errors;
                    });
                    return errors;
                }
        ).onErrorReturn(t -> {
            //do some stuff
            return responseBody;
        });

Upvotes: 0

Related Questions