Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RxJava + Retrofit - make multiple calls

Tags:

I have a solid grasp of Retrofit when using sync and async calls. However, I encountered a small problem when creating some complex task, which I have to:

  1. Make a request in order to get List of ID's(about 20-30 ID's)
  2. After fetching ID's list, I would like to make async calls in order to get information about each object, defined by ID. I want to make 20-30 request in pararrel. I desire to observe it in order to update the UI after I manage to receive all the data from async calls.

I read about that issue and I realized that RxJava would solve my problem. But frankly, I have found it really hard so far to understand the whole process.

It would be great if I read some correct example in order to immerse into RxJava/RxAndroid issue.

like image 796
Arek Biela Avatar asked Jun 01 '15 13:06

Arek Biela


2 Answers

With this example you can get a list of ids, divide it in individual observables, call a service for each individual id and get notified n times for each getDetails response.

service.getIds()         .flatMap(ids -> Observable.from(ids))         .map(id -> service.getDetails(id))         .subscribe(detailed -> updateUi(detailed)); 

You can use the Observable.zip function to wait on several parallel calls, but I don't know if you can use it in a variable size call.

Take a look at this example:

Retrofit support for Observable also makes it easy to combine multiple REST calls together. For example, suppose we have one call that gets the photo and a second that gets the metadata. We can zip the results together:

Observable.zip(     service.getUserPhoto(id),     service.getPhotoMetadata(id),     (photo, metadata) -> createPhotoWithData(photo, metadata))     .subscribe(photoWithData -> showPhoto(photoWithData)); 
like image 180
ffleandro Avatar answered Sep 21 '22 06:09

ffleandro


It seems like what you're really looking for is info or examples on how to get started with RxJava, so I'd suggest you have a look at this excellent series of articles by Dan Lew: http://blog.danlew.net/2014/09/15/grokking-rxjava-part-1/

This series should contain enough material to give you a good idea of how to implement your feature.

like image 31
memoizr Avatar answered Sep 23 '22 06:09

memoizr