Skip to content

Instantly share code, notes, and snippets.

@amitshekhariitbhu
Last active February 1, 2017 11:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save amitshekhariitbhu/3203970442ebdfa8aec44fc4381cb5ac to your computer and use it in GitHub Desktop.
Save amitshekhariitbhu/3203970442ebdfa8aec44fc4381cb5ac to your computer and use it in GitHub Desktop.
/* Here first of all, we get the list of users from server.
* Then for each userId from user, it makes the network call to get the detail
* of that user.
* Finally, we get the userDetail for the corresponding user one by one
*/
/*
* This observable return the list of users.
*/
private Observable<List<User>> getUserListObservable() {
return RxAndroidNetworking.get("https://fierce-cove-29863.herokuapp.com/getAllUsers/{pageNumber}")
.addPathParameter("pageNumber", "0")
.addQueryParameter("limit", "10")
.build()
.getObjectListObservable(User.class);
}
/*
* This observable return the userDetail corresponding to the user.
*/
private Observable<UserDetail> getUserDetailObservable(long userId) {
return RxAndroidNetworking.get("https://fierce-cove-29863.herokuapp.com/getAnUserDetail/{userId}")
.addPathParameter("userId", String.valueOf(userId))
.build()
.getObjectObservable(UserDetail.class);
}
/*
* This method do the magic - first gets the list of users
* from server.Then, for each user, it makes the network call to get the detail
* of that user.
* Finally, we get the UserDetail for the corresponding user one by one
*/
public void flatMap() {
getUserListObservable()
.flatMap(new Func1<List<User>, Observable<User>>() { // flatMap - to return users one by one
@Override
public Observable<User> call(List<User> usersList) {
return Observable.from(usersList); // returning user one by one from usersList.
}
})
.flatMap(new Func1<User, Observable<UserDetail>>() {
@Override
public Observable<UserDetail> call(User user) {
// here we get the user one by one
// and returns corresponding getUserDetailObservable
// for that userId
return getUserDetailObservable(user.id);
}
})
.subscribeOn(Schedulers.newThread())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Observer<UserDetail>() {
@Override
public void onCompleted() {
// do something onCompleted
}
@Override
public void onError(Throwable e) {
// handle error
}
@Override
public void onNext(UserDetail userDetail) {
// here we get userDetail one by one for all users
Log.d(TAG, "userDetail id : " + userDetail.id);
Log.d(TAG, "userDetail firstname : " + userDetail.firstname);
Log.d(TAG, "userDetail lastname : " + userDetail.lastname);
}
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment