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.
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();
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:
Remember to add a stop condition in the onNext
to not end up with an infinite loop.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With