Search code examples
android-recyclerviewandroid-lifecycleandroid-livedata

How to use DataBinding with LiveData inside RecyclerView


So DataBinding can now use LiveData in its binding. As part of this, we also have to set to the Data Binding the life cycle like so:

SampleLayoutBinding binding = DataBindingUtil.inflate(this, R.layout.sample_layout)
binding.setLifeCycleOwner(this)

My question is what is the proper way to set this lifecycle owner inside recyclerview? Or even more appropriately, do we need to set the LifeCyclerOwner when using data binding inside recyclerview?


Solution

  • Yes, you need to set LifeCycleOwner to your data-binding. For this purpose you need to pass Activity/Fragment to your RecyclerView.Adapter as LifeCycleOwner interface and set it when you create binding in RecyclerView.Adapter.onCreateViewHolder().
    You also can use your own implementation of LifeCycleOwner