title: ViewBinding in Fragment - Memory Leak or even NullPointerException possible?
body: <p>The <a href="https://developer.android.com/topic/libraries/view-binding#fragments" rel="nofollow noreferrer">official documentation</a> shows a code sample in which the binding property is set to <code>null</code> in <code>onDestroyView()</code>.</p>
  <p>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.</p>
  <p>My question is are there scenarios where missing to set the binding property to <code>null</code> can cause a <code>NullPointerException</code>?</p>
  <p>After this general question I want ask the same questions based on this concrete code sample avoiding the <code>binding</code> property in the first place:</p>
  <pre><code>class SampleFragment : Fragment()
  {
      private val viewModel by sharedViewModel&lt;SampleViewModel&gt;()
  
      override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View =
              FragmentSampleBinding.inflate(inflater, container, false).apply {
                  sampleTextView.text = &quot;foo&quot;
  
                  viewModel.sampleLiveData.observe(viewLifecycleOwner, Observer { sampleText -&gt;
                      sampleTextView.text = sampleText
                  })
              }.root
  }
  </code></pre>
  <p>I'm not holding a property. The scope of the binding is limited to</p>
  <ol>
  <li><code>onCreateView()</code></li>
  <li>the callback of the live data observer</li>
  </ol>
  <p>While 1. doesn't seem to be critical. I'm wondering if 2. is safe.</p>
  <ul>
  <li><p>Regarding memory leaks - I think the live data observing scope also is bound to the view lifecycle via <code>viewLifecycleObserver</code>. So if there were a memory leak it could not be for long.</p>
  </li>
  <li><p>Regarding a <code>NullPointerException</code>?</p>
  </li>
  </ul>