从 Flowable Room ORM 发出每个项目
Emit each item from Flowable Room ORM
我在 Room ORM 中有一个项目列表,我想将其显示在 Recycler 视图中。数据正在从网络添加到数据库。问题是每次从 Flowable 发出整个列表而不是每个项目时我都会得到。我试过 .distinctUntilChanged 没有任何区别。
@Query("SELECT * FROM items")
Flowable<List<Item>> getItems();
我也试过 return 只有一个项目只加载第一个是数据库的项目。
您可以使用 flatMap
获取项目流。
itemDao.getItems().flatMap(list -> {
Item[] items = new Item[list.size()];
list.toArray(items);
return Flowable.fromArray(items);
}).subscribe(item -> {
// Now you can do with each item.
});
如果您只需要第一项:
itemDao.getItems().flatMap(list -> {
Item[] items = new Item[list.size()];
list.toArray(items);
return Flowable.fromArray(items);
})
.firstElement()
.subscribe(first -> {
// Now you can do with the first one.
});
是的,Flowable<List<Item>>
意味着您将在列表更改时收到一个回调:这就是 Room 的工作原理。通常,您将该列表传递给 DiffUtil
,然后生成更新您的 RecyclerView
.
所需的一组更改
您可以使用 flatMap
和 Flowable.fromIterable()
映射到 Flowable
,这将一一发出所有项目
getItems()
.flatMap(Flowable::fromIterable)
.subscribe(item -> {
});
就是这样。简短而干净的代码,无需转换 toArray
我在 Room ORM 中有一个项目列表,我想将其显示在 Recycler 视图中。数据正在从网络添加到数据库。问题是每次从 Flowable 发出整个列表而不是每个项目时我都会得到。我试过 .distinctUntilChanged 没有任何区别。
@Query("SELECT * FROM items")
Flowable<List<Item>> getItems();
我也试过 return 只有一个项目只加载第一个是数据库的项目。
您可以使用 flatMap
获取项目流。
itemDao.getItems().flatMap(list -> {
Item[] items = new Item[list.size()];
list.toArray(items);
return Flowable.fromArray(items);
}).subscribe(item -> {
// Now you can do with each item.
});
如果您只需要第一项:
itemDao.getItems().flatMap(list -> {
Item[] items = new Item[list.size()];
list.toArray(items);
return Flowable.fromArray(items);
})
.firstElement()
.subscribe(first -> {
// Now you can do with the first one.
});
是的,Flowable<List<Item>>
意味着您将在列表更改时收到一个回调:这就是 Room 的工作原理。通常,您将该列表传递给 DiffUtil
,然后生成更新您的 RecyclerView
.
您可以使用 flatMap
和 Flowable.fromIterable()
映射到 Flowable
,这将一一发出所有项目
getItems()
.flatMap(Flowable::fromIterable)
.subscribe(item -> {
});
就是这样。简短而干净的代码,无需转换 toArray