Reputation: 1
I have 3 methods in my Room Database
Flowable<List<Book>> getBooks() {....}
Flowable<List<Author>> getAuthors(int bookId) {....}
Flowable<List<Category>> getCategories(int bookId) {....}
The Book object
Book {int id; List<Author> authors; List<Category> categories}
I am trying to do something like
Flowable<List<Book>> getBookFullBooks() {
return getBooks()
//1. get the list of books from flowable??
//2. get each book from the list??
//3. set properties of each book from getAuthors(book.id) and
// getCategories(book.id)
// Something like:
.switchMap(book -> _getCategories(book.id).map(categories -> {
book.categories = categories;
return book;
}))
.switchMap(book -> _getAuthors(book.id).map(authors -> {
book.authors = authors;
return book;
}));// collect the books into a sequentioal Flowable<List<Book>>
}
//4. then return all the books as Flowable<List<Book>>
I have been trying to do so but without any success. How can we do that?
Upvotes: 0
Views: 657
Reputation: 3253
I would do something like this
getBooks()
.flatMapSingle(bookList -> Flowable.fromIterable(bookList)
.flatMap(book -> getCategories(book.id)
.map(categories -> {
book.setCategories(categories);
return book;
}))
.flatMap(book -> getAuthors(book.id)
.map(authors -> {
book.setAuthors(authors);
return book;
}))
.toList())
.subscribe(bookList -> {
// done
});
I think it didn't work on the first time because your Flowable<List<Book>>
didn't complete and toList()
got stuck. Try to nest the flatMaps, it should work not because Flowable.fromIterable()
completes after its done looping.
I created test like this and it works fine https://pastebin.com/Fus4MvXW
Upvotes: 1