Skip to content Skip to sidebar Skip to footer

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 succ

Solution 1:

Observable.range(1, 50)
    .flatMap(index ->// for every index make new requestmakeRequest(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 success1// limit concurrency to single request-save
    )
    .subscribe();

Solution 2:

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.

Solution 3:

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

You can use range operator and handle each Int emitted.

if the transaction is successful, I have to increase my index

In that case you need to use concatMap operator. It handles each Observable sequentially.

Observable<Response> makeRequest(int i) {...}

Completable saveToDb(Response response) {...}

Observable.range(1, 50)
    .concatMap(i -> makeRequest(i)
                        //I assume that you save your response to DB asynchronously//if not - use doOnNext operator instead of flatMapCompletable.flatMapCompletable(response -> saveToDb(response)
                        .toObservable())
    .retry()
    ...

Post a Comment for "How To Repeat Same Network Request Multiple Times(different Parameters) In Rxjava/rxandroid?"