Android Rx: Multiple API requests non-blocking

31 Views Asked by At

I'm using Rx+Retrofit in my project. Going to create so-called API cache to keep failed POST requests. Then I need to send cached requests again. So what is the best way to handle of queue of different API requests using Rx? The request queue should not be blocked if some requests will failed. Maybe Rx has some better approach instead of simple recursion. Thanks.

1

There are 1 best solutions below

0
Rabi Rafique On

You can use the retryWhen operator along with custom logic to retry the failed requests.

Create a Class for API Caching/ Use PublishSubject for Queue/ Implement the Retry Logic

 PublishSubject<ReqType> requestQueue = PublishSubject.create();

 requestQueue.flatMap(request -> {
   
    return apiService.makePostRequest(request)
        .retryWhen(errors -> errors
            .flatMap(error -> {
                if (shouldRetry(error)) {
                    // Retry the request after a delay
                    return Observable.timer(timeinmillis, TimeUnit.SECONDS);
                } else {
                    // Don't retry. propagate the error
                    return Observable.error(error);
                }
            })
        );
})
.subscribe(
    response -> {
        // Handle the successful response
    },
    throwable -> {
        // Handle the final error after retries
    }
);

Whenever you want to make a POST request, enqueue it using requestQueue.onNext(req).