zzq
zzq

Reputation: 181

how to write nested network request use rxjava + retrofit2

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?

Upvotes: 2

Views: 644

Answers (1)

david.mihola
david.mihola

Reputation: 13012

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(...);

Upvotes: 8

Related Questions