Search code examples
androidsqliteandroid-recyclerviewrx-javamvp

How to load data into RecyclerView from DB using RxJava? (MVP + RxJava + SQLite)


There is RecyclerViewAdapter which show items(this items have already mapped in database).

RecyclerViewAdapter contains reference to Presenter to load items. Also it contains ArrayList with items ID.

How to load item using Rx? How should looks right code for onBindViewHolder method?

Now it looks like:

List<Long> ItemIds; 
Presenter presenter;
public void onBindViewHolder(ViewHolder holder, int position) {
   Long itemId = ItemIds.get(position);
   Item item = presenter.getItemById(itemId); //loading from DB
   holder.setContent(item);
}

P.S.

  • Each item stores pretty mush information so I guess this is bad idea to keep all full item objects in RecyclerView (maybe I'm wrong??? and this is okey).
  • I know how to load items in background thread using Rx but I'm confused by this decision. I can create subscriber in RecyclerView and pass it to presenter layer where it will be subscribed to observable which will emit Item from DB. Is it acceptable solution?

Solution

  • First of all, I have to mention that as long as you want to load data from DB you have to get ready for a laggy UI cause by lack of speed in I/O.

    I don't have any idea about how big is your data but in worst case you can load it to memory page by page. However, Android devices are not a good solution for big data management.

    By the way, creating observable inside Adapter (i.e. View) is not a good idea and they must be created in your business logic (e.g. API Service / DB or Presenter layer.

    In this repo you can find a good sample of Android Application developed by MVP with Ormlite Database mash-up using RxJava and Dagger:

    https://github.com/mmirhoseini/marvel

    I hope it helps :)