2

I am using Rxjava and Retrofit2.0 in my project, it looks like this:

Observable<List<A>>  getAFromServer();
Observable<List<B>>  getBFromServer(@Body A.a);

If I don't use reactive way, it will be like this:

List<A> listA = getAFromServer();
foreach(A a: listA){
        getBFromServer(a.a)
}

So, my question is how to use Rxjava to achieve this and what operator to use?

2
  • 2
    see this question: stackoverflow.com/questions/26356852/… Commented Mar 29, 2016 at 2:53
  • Fixed language related things and spaces. Commented Mar 29, 2016 at 3:40

1 Answer 1

8

With Rx you can finally stop thinking about "nesting" network requests.

If you think about it, you never really wanted to "nest" network requests, right? That was only how the code ended up looking because you had only AsyncTasks or other callbacks at your disposal.

With Rx you can finally write code that in its structure resembles what you actually want to, which is chain network requests: First do one thing, then do another.

getAFromServer()
    .flatMap(new Func1<List<A>, Observable<A>>() {       
        @Override
        public Observable<A> call(List<A> list) {
            // the first flatMap is just a trick to "flatten" the Observable
            return Observable.from(list);
        }
    })
    .flatMap(new Func1<A, Observable<B>>() {
        @Override
        public Observable<A> call(A someA) {
            return getBFromServer(someA.a);
        }

    })
    .subscribe(...);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.