Should I pass Fragment instance or owner returned from getViewLifecycleOwner when calling setLifecycleOwner on data binding Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of Should I pass Fragment instance or owner returned from getViewLifecycleOwner when calling setLifecycleOwner on data binding without wasting too much if your time.

The question is published on by Tutorial Guruji team.

Which approach is correct:

  1. Passing Fragment instance as lifecycleOwner:

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View {
        val binding = FragmentEventSettingsBinding.inflate(inflater, container, false)
        binding.lifecycleOwner = this
        return binding.root
    }
    
  2. Passing viewLifecycleOwner of the Fragment:

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View {
        val binding = FragmentEventSettingsBinding.inflate(inflater, container, false)
        binding.lifecycleOwner = viewLifecycleOwner
        return binding.root
    }
    

Answer

The recommended solution is to use fragment’s view lifecycle via getViewLifecycleOwner() or getViewLifecycleOwnerLiveData() which were added in Support Library 28.0.0 and AndroidX 1.0.0, so that LiveData will remove observers every time the fragment’s view is destroyed

Reference: 5 common mistakes when using Architecture Components

We are here to answer your question about Should I pass Fragment instance or owner returned from getViewLifecycleOwner when calling setLifecycleOwner on data binding - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji