Kim
Kim

Reputation: 5445

Retrofit + RxJava: How to request for multiple request in order and assemble results in single Observable?

I am using RxJava + Retrofit.

For example, there are Article

public class Article {
    private Long articleId;
    private Long userId;
    private String image;
    private String text;
    ...
}

and User

public class User {
    private Long userId;
    private String userName;
    private String image;
    ...
}

And there are two sevices

I want to list 10 articles, and related author user information, assemble them into something like Observable<List<Pair<Article, User>>>, is it possible?

Upvotes: 3

Views: 1242

Answers (2)

Tassos Bassoukos
Tassos Bassoukos

Reputation: 16152

This should do the trick:

listArticles(int pageIdx, int pageMax)
.flatMapIterable(list->list)
.flatMap(article ->
     getUserByUserIds(article.userId)
     .subscribeOn(Schedulers.io())
     .flatMapIterable(list->list),
     Pair::of
)
.toList();

However, the API is badly specced; Observables already have an innate ordering, no need to wrap everything in a List. getUserByIds - will it return a single user or multiple users? Why not have a single id to User method? Why aren't the IDs in the domain objects primitives? Do you expect to have items without IDs?

Upvotes: 2

Blackbelt
Blackbelt

Reputation: 157487

One way could involve the use of the zip operator, which can combine multiple Observables together. You can read more here. Just pass the two observable to zip operator

Upvotes: 0

Related Questions