简体   繁体   中英

Room DataSource.Factory with multiple view RecyclerView

I have the following SELECT on the DAO

@Query("SELECT * FROM todo ORDER BY time DESC")
abstract DataSource.Factory<Integer, TodoItem> getAll();

I have a repository that just returns the above. And in the model I have

PagedList.Config config = new PagedList.Config.Builder()
            .setEnablePlaceholders(false)
            .setInitialLoadSizeHint(40)
            .setPageSize(20)
            .build();

todos = new LivePagedListBuilder<>(todoRepository.getAll(), config).build();

The Fragment simply observes the above todos and calls adapter.submitList(items) on new updates.

I just recently switched to using the androidx.paging , before I was getting all the data and populating the RecyclerView with it.

The above code works fine for what it currently is. The problem is that I need support for multiple views. More exactly, I need to add the date on top of the first element with that date. Prior to the upgrade, I was looping the items and adding DateHeader items where needed (and handling multiple view types in the Adapter), but with this new method I cannot edit what DataSource.Factory provides.

Using ItemDecoration or adding the date in every item and changing its visibility are not an option.

I have the date saved in the database as well, so I can group by and get the item count by date if that can be of any help.

Is there a way to solve this? Just for reference, there is no network communication here, everything is local and saved only in the database.

Seems like there is currently no support for adding additional items to the list that DAO's DataSource.Factory returns.

Since all I needed was to add the date on top of the first item with that date I ended up solving this using SQLite.

Here is the query if it may help somebody:

select * from (
    select tDate.*, 0 as type from todos as tDate group by date having max(time) 
  UNION 
    select tItem.*, 1 as type from todos tItem
  ) as tView 
order by tView.time desc, tView.type asc

I defined the above query as a DatabaseView .

Thankfully PagedListAdapter just like a regular Adapter has support for multiple views, in case the type is 0 from above I print a date item, otherwise I print a regular item.

This is not the best solution, but it's the only one I managed to make it work just like a regular RecycleView with multiple types.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM