我的会议室数据库中有3种方法
Flowable<List<Book>> getBooks() {....}
Flowable<List<Author>> getAuthors(int bookId) {....}
Flowable<List<Category>> getCategories(int bookId) {....}
Book对象
Book {int id; List<Author> authors; List<Category> categories}
我正在尝试做类似的事情
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>>
我一直在尝试这样做,但是没有成功。我们该怎么做?
答案 0 :(得分:1)
我会做这样的事情
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
});
我认为这是第一次无效,因为您的Flowable<List<Book>>
未完成并且toList()
被卡住了。尝试嵌套flatMap,因为Flowable.fromIterable()
在完成循环后完成,因此它应该无法工作。
我创建了这样的测试,效果很好 https://pastebin.com/Fus4MvXW