ViewBinding in Fragment - Memory Leak or even NullPointerException possible?

Viewed 324

The official documentation shows a code sample in which the binding property is set to null in onDestroyView().

The obvious reason to me is that fragments whose view has been destroyed but have not been destroyed can release the memory for their view. This memory would leak if the fragment still had a reference to the binding, which itself holds references to the views.

My question is are there scenarios where missing to set the binding property to null can cause a NullPointerException?

After this general question I want ask the same questions based on this concrete code sample avoiding the binding property in the first place:

class SampleFragment : Fragment()
{
    private val viewModel by sharedViewModel<SampleViewModel>()

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View =
            FragmentSampleBinding.inflate(inflater, container, false).apply {
                sampleTextView.text = "foo"

                viewModel.sampleLiveData.observe(viewLifecycleOwner, Observer { sampleText ->
                    sampleTextView.text = sampleText
                })
            }.root
}

I'm not holding a property. The scope of the binding is limited to

  1. onCreateView()
  2. the callback of the live data observer

While 1. doesn't seem to be critical. I'm wondering if 2. is safe.

  • Regarding memory leaks - I think the live data observing scope also is bound to the view lifecycle via viewLifecycleObserver. So if there were a memory leak it could not be for long.

  • Regarding a NullPointerException?

0 Answers
Related