Please note that all this works over the Paging with network google sample. Although that, the idea is there.
@Sarquella helped me with this solution. Add this classes to your project. Basically we are extending ViewHolder
to be LifeCycle Owner
, as it is already done by default with Activities
and Fragments
.
The LifecycleViewHolder
:
abstract class LifecycleViewHolder(itemView: View) :
RecyclerView.ViewHolder(itemView),
LifecycleOwner {
private val lifecycleRegistry = LifecycleRegistry(this)
fun onAttached() {
lifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_START)
}
fun onDetached() {
lifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_STOP)
}
override fun getLifecycle(): Lifecycle = lifecycleRegistry
}
LifecycleOwner
is a single method interface that denotes that the class has a Lifecycle
. You can find more information here.
The LifecyclePagedListAdapter
:
abstract class LifecyclePagedListAdapter<T, VH : LifecycleViewHolder>(diffCallback: DiffUtil.ItemCallback<T>) :
PagedListAdapter<T, VH>(diffCallback) {
override fun onViewAttachedToWindow(holder: VH) {
super.onViewAttachedToWindow(holder)
holder.onAttached()
}
override fun onViewDetachedFromWindow(holder: VH) {
super.onViewDetachedFromWindow(holder)
holder.onDetached()
}
}
The LifecycleAdapter
(in the case you need it):
abstract class LifecycleAdapter<VH : LifecycleViewHolder> :
RecyclerView.Adapter<VH>() {
override fun onViewAttachedToWindow(holder: VH) {
super.onViewAttachedToWindow(holder)
holder.onAttached()
}
override fun onViewDetachedFromWindow(holder: VH) {
super.onViewDetachedFromWindow(holder)
holder.onDetached()
}
}
Then, extends MyAdapter
to LifecyclePagedListAdapter<MyEntity, LifecycleViewHolder>(MY_COMPARATOR)
and MyViewHolder
to LifecycleViewHolder(view)
. You'll have to complete your classes based on what we have changed, accordingly. Now we can observe to a liveData
object on MyViewHolder
class. So we can add this to MyViewHolder
class (assuming you're using Dependency Injection). Basically, we'll do the same we do for Fragments
or Activities
:
private lateinit var myViewModel: MyViewModel
init {
(itemView.context as? AppCompatActivity)?.let{
myViewModel = ViewModelProviders.of(it).get(MyViewModel::class.java)
}
}
Then, inside the bind()
method:
fun bind(myCell: MyEntity?) {
myViewModel.myLiveData.observe(this, Observer {
// Buala!! Check if it is the cell you want to change and update it.
if (it != null && myCell != null && it.id == myCell.id) {
updateCell(it)
}
})
}
Updating Paged Data
, last paragraph – GisbornePagedListAdapter
? if so, whats yourDiffCallback
like? – Gisborne