Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to repeat same network request multiple times(different parameters) in RxJava/RxAndroid?

So, I have a /download API which returns me a generic Object (based on an index number which is its own parameter) then I have to save it to my database, if the transaction is successful, I have to increase my index and repeat the same process again, otherwise retry().

I'll need to repeat this for about 50 times.

How can I achieve this process using Rx-Java? I'm stuck right now. Any help would be awesome. Thank You.

like image 285
Sanjay Gubaju Avatar asked Mar 11 '23 01:03

Sanjay Gubaju


2 Answers

Observable.range(1, 50)
    .flatMap(index ->      // for every index make new request
        makeRequest(index) // this shall return Observable<Response>
            .retry(N)      // on error => retry this request N times
    )
    .subscribe(response -> saveToDb(response));

Answer to comment (make new request only after previous response is saved to db):

Observable.range(1, 50)
    .flatMap(index ->      // for every index make new request
        makeRequest(index) // this shall return Observable<Response>
            .retry(N)      // on error => retry this request N times
            .map(response -> saveToDb(response)), // save and report success
        1                  // limit concurrency to single request-save
    )
    .subscribe();
like image 60
Yaroslav Stavnichiy Avatar answered Apr 07 '23 04:04

Yaroslav Stavnichiy


If I understand you correctly this piece of code should point you to a right direction.

        BehaviorSubject<Integer> indexes = BehaviorSubject.createDefault(0);
        indexes.flatMap(integer -> Observable.just(integer)) // download operation
               .flatMap(downloadedObject -> Observable.just(integer)) // save operation
               .doOnNext(ind -> indexes.onNext(ind + 1))
               .subscribe(ind -> System.out.println("Index " + ind));

What happens is:

  1. BehaviorSubject is a sort of initiator of whole work, it feeds indexes to the chain.
  2. First flatMap is where you do a download operation
  3. Second flatMap is where you save it to a DB
  4. In doOnNext you have to issue onNext or onComplete to the subject to continue with or finish processing. (This can be done in a subscriber)

Remember to add a stop condition in the onNext to not end up with an infinite loop.

like image 25
MatBos Avatar answered Apr 07 '23 05:04

MatBos