4
votes

I have a list of items in the Room ORM which I would like to display in a Recycler view. The data is being added from the network to the db. The problem is I am getting every time the whole list emited from the Flowable and not each item. I have tried with .distinctUntilChanged with no difference.

@Query("SELECT * FROM items")
Flowable<List<Item>> getItems();

I have tried also to return only a single item which loads only the first one that is the db.

3
You can use flatMap() to get Flowable<Item> from Flowable<List<Item>> - Quang Nguyen

3 Answers

3
votes

You can use flatMap to get stream of items.

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.

    });

If you only need the first 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.

        });
12
votes

Yes, Flowable<List<Item>> means you'll get a single callback when the list changes: this is how Room works. Generally, you'd pass that list into DiffUtil, which then generates the set of changes needed to update your RecyclerView.

4
votes

You can use flatMap and Flowable.fromIterable() to map to Flowable which will emit all items one by one

getItems()
    .flatMap(Flowable::fromIterable)
    .subscribe(item -> {

    });

That's it. Short and clean code, without casting toArray