We are using ReactiveX and Retrofit in our network stack to handle all API requests in an asynchronous way.
Our goal is to create one method that will return a completely populated collection of User
models. Each User
model has a list of Pet
objects. We can fetch all of the User
models with one request. However, Pet
models need to be requested per User
.
Getting users is simple:
// Service.java
@GET("users/?locationId={id}")
Observable<List<User>> getUsersForLocation(@Path("id") int locationId);
@GET("pets/?userId={id}")
Observable<List<Pet>> getPetsForUser(@Path("id") int userId);
// DataManager.java
public Observable<List<User>> getUsersForLocation(int locationId) {
return api.getUsersForLocation(locationId);
}
public Observable<List<Pet>> getPetsForUser(int userId) {
return api.getPetsForUser(userId);
}
We would like to find some convenient (RX style) way of looping through the User
list, fetching the Pet
s for that each user, assigning them to the User
and ultimately returning the Observable<List<User>>
.
I am fairly new to RX. I've looked over the documentation and have tried using various methods such as flatMap()
and zip
, however, I have yet to find the exact combination of transforms or combiners to make it happen.
I wrote a small sample app that makes what you are trying to achieve. Here the components:
Pet class:
User class:
Put all together:
It produces:
If it doesn't answer you question please post you actual datamodel for User and Pet.