0

I have a Fragment that’s using View Binding, so it sets its _binding member variable in onCreateView and nulls it out in onDestroyView. In onViewCreated, I observe a LiveData from the view model using viewLifecycleOwner as the LifecycleOwner. (In reality this is split between a fragment and a base class, but I can’t see how that would explain any of this)

I can’t reproduce this in house, but crashlytics is reporting cases in the field where the LiveData’s observer is getting called back when the binding is null, making me think that somehow it’s being called after onDestroyView has been called. Any idea how that’s possible?

UPDATE: Turns out the observer was calling postDelayed on one of the views, so the Runnable was being executed (and accessing the binding) after onDestroyView had been called.

Thanks to @Zain and @EpicPandaForce for taking a look.

Aidan64
  • 573
  • 1
  • 5
  • 12
  • Probably because `MyFragmentBase` is extended by multiple fragments; so whenever the `onDestroyView()` get called in `MyFragment`; and you got to another fragment for the same base class; then this doesn't mean that the observer is detached; it's still working as it's tied to the lifecycle of the ViewModel; not the fragment. – Zain Nov 03 '21 at 17:42
  • Doesn't `observe(viewLifecycleOwner)` mean that the observer is tied to the lifecycle of the fragment? – Aidan64 Nov 03 '21 at 19:06
  • I'd need to see the exact exception stack trace of the NPE to tell you what went wrong. I have a feeling it's a matter of process death + fragment recreation, and has nothing to do with LiveData per say. – EpicPandaForce Nov 08 '21 at 13:19
  • If this really was a bug in LiveData, I was considering making the jump to Flow + flowWithLifecycle/repeatOnLifecycle, but if it is indeed something with process death then perhaps that wouldn't help either. – Aidan64 Nov 09 '21 at 15:56

0 Answers0