HelloCW
HelloCW

Reputation: 2295

Should I add binding.lifecycleOwner=this when I use viewModel?

In my mind, I should add binding.lifecycleOwner=this when I use viewModel.

I find many projects such as Code A doesn't add binding.lifecycleOwner=this, why?

The Code A is from the project https://github.com/enpassio/Databinding

Code A

class AddToyFragment : androidx.fragment.app.Fragment() {

    private lateinit var binding: AddToyBinding
    ...

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

        setHasOptionsMenu(true)

        return binding.root
    }

    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)
        (requireActivity() as AppCompatActivity).supportActionBar?.setDisplayHomeAsUpEnabled(true)

        //If there is no id specified in the arguments, then it should be a new toy
        val chosenToy : ToyEntry? = arguments?.getParcelable(CHOSEN_TOY)

        //Get the view model instance and pass it to the binding implementation
        val factory = AddToyViewModelFactory(provideRepository(requireContext()), chosenToy)
        mViewModel = ViewModelProviders.of(this, factory).get(AddToyViewModel::class.java)

        binding.viewModel = mViewModel

        binding.fab.setOnClickListener {
            saveToy()
        }

        binding.lifecycleOwner=this //I think it should add 
    }

Upvotes: 11

Views: 10391

Answers (2)

Kubick
Kubick

Reputation: 61

as far as I understand it,

binding.lifecycleOwner= this

used in one side to make a subscription to receive messages when liveData is changed (so information in view to be consistent), and in another side to delete observer from list when view and fragment is destroyed (to prevent memory leaks). Fragment's viewLifecycleOwner is more suitable to use as lifecycleOwner for binding in this way, isn't it?

Upvotes: 4

Stanislav Bondar
Stanislav Bondar

Reputation: 6265

binding.lifecycleOwner used for observing LiveData with data binding. Kind of android:text=@{viewModel.text} where val text:LiveData<String>. View will observe text changes at runtime.

Upvotes: 23

Related Questions