HelloCW
HelloCW

Reputation: 2295

Must I set lifecycleOwner for a data binding in Android Studio?

binding is a data binding, I set the lifecycle owner to the lifecycle of the view.

Is it necessary ?

It seems that the app can work well if I remove binding.lifecycleOwner = this.viewLifecycleOwner.

Code

class FragmentHome : Fragment() {

   private lateinit var binding: LayoutHomeBinding

   override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        binding = DataBindingUtil.inflate(
            inflater, R.layout.layout_home, container, false
        )

        // Set the lifecycle owner to the lifecycle of the view
        binding.lifecycleOwner = this.viewLifecycleOwner   //Must I set lifecycleOwner for a data binding?

        ...
   }

}

Upvotes: 3

Views: 3481

Answers (1)

Saurabh Thorat
Saurabh Thorat

Reputation: 20714

If you are using a LiveData object with your binding class, it is required to set a lifecycle owner to define the scope of the LiveData object.

So if you have a LiveData object like:

private val _name = MutableLiveData("John")
val name: LiveData<String> = _name

And you use it for binding like:

android:text="@{vm.name}"

Then you need to specify a lifecycle owner.

Upvotes: 9

Related Questions