R
R
robert_n2017-01-11 14:30:49
Java
robert_n, 2017-01-11 14:30:49

How to make a request in rxJava?

I have 3 tables: Article, User and Category. The Article table stores all articles, User - application users, and Category - categories of articles. Article table structure

title-> String
content-> String
category -> Category.id
autor ->User.id

I need to get all the articles, as well as information about which category it belongs to and about the author of this article. All this data is in the local database and should be displayed in the recyclerView.
I wrote 3 methods that fetch data from the local DB and return an Observable:
public Observable<List<Article>> getArticles() {
        return articleSqlRepository.query(new articlesAllSpecification());
    }


 public Observable<User> geUser(String userId) {
// Получить информацию об авторе статьи, используя его id                
        return userSqlRepository.query(new UserByIdSpecification(userId)); 

    }

 public Observable<Category> getCategory(String categoryId) {
// Получить информацию о категории
        return categorySqlRepository.query(new CategoryByIdSpecification(categoryId)); 

    }

Next, I call a method that should return a list of articles List. But I ran into a problem that I don’t know how to combine requests correctly. The fact is that I first have to get a list of all articles, and then for each specific article, find information about its category and author.
public void getArticleItems()
{
// Список статей, для отображения в RecyclerView
List<ArticleItem> articleItemLists = new ArrayList<>();
// Получить список всех статей
getArticles()
// Последовательно обработать все статьи
   .flatMap(Observable::from)
// Что делать дальше?
}

And here's the problem: what operator to use to concatenate 2 Observables (getUser() and getCategory()) so that you can refer to the article object from the previous query result.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
Denis Zagaevsky, 2017-01-11
@robert_n

Next your need

.switchMap(article -> Observable.zip(
    getUser(...).first(), 
    getCategory(...).first(),
     (user, category) -> { return new ArticleItem(...); })
.toList()
.subscribe(listOfArticleItems -> ...);

For all operators, read the documentation, it will become clearer.
By the way, it is convenient to use the StorIO reactive wrapper to work with the database, and not to fence your crutches.

T
Tiberal, 2017-01-11
@Tiberal

it all depends on how you want to combine them. choose your case.
https://github.com/ReactiveX/RxJava/wiki/Combining...
at first glance you need a zip

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question