Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- @Dao
- interface ConcertDao {
- // The Integer type parameter tells Room to use a PositionalDataSource
- // object, with position-based loading under the hood.
- @Query("SELECT * FROM user ORDER BY concert DESC")
- fun concertsByDate(): DataSource.Factory<Int, Concert>
- }
- class MyViewModel(concertDao: ConcertDao) : ViewModel() {
- val concertList: LiveData<PagedList<Concert>> = LivePagedListBuilder(
- concertDao.concertsByDate(),
- /* page size */ 20
- ).build()
- }
- class MyActivity : AppCompatActivity() {
- public override fun onCreate(savedState: Bundle?) {
- super.onCreate(savedState)
- val viewModel = ViewModelProviders.of(this)
- .get(MyViewModel::class.java!!)
- val recyclerView = findViewById(R.id.concert_list)
- val adapter = ConcertAdapter()
- viewModel.concertList.observe(this, { pagedList ->
- adapter.submitList(pagedList) })
- recyclerView.setAdapter(adapter)
- }
- }
- class ConcertAdapter() :
- PagedListAdapter<Concert, ConcertViewHolder>(DIFF_CALLBACK) {
- fun onBindViewHolder(holder: ConcertViewHolder, position: Int) {
- val concert = getItem(position)
- if (concert != null) {
- holder.bindTo(concert)
- } else {
- // Null defines a placeholder item - PagedListAdapter automatically
- // invalidates this row when the actual object is loaded from the
- // database.
- holder.clear()
- }
- }
- companion object {
- private val DIFF_CALLBACK = object : DiffUtil.ItemCallback<Concert>() {
- // Concert details may have changed if reloaded from the database,
- // but ID is fixed.
- override fun areItemsTheSame(oldConcert: Concert,
- newConcert: Concert): Boolean =
- oldConcert.id == newConcert.id
- override fun areContentsTheSame(oldConcert: Concert,
- newConcert: Concert): Boolean =
- oldConcert == newConcert
- }
- }
- }
Add Comment
Please, Sign In to add comment