Hi there Why I need to make the binding instance ...
# android
u
Hi there Why I need to make the binding instance to null in onDestroyView
Copy code
override fun onDestroyView() {
    super.onDestroyView()
    _binding = null
}
Does the garbage collection type thing not works with viewbindig ? Or I am on wrong track Please advise
😶 3
👍 2
c
Short answer: because the Fragment lifecycle is the worst. Longer answer: bad things happen when async processes attempt to update the UI after
onDestroyView()
. Clearing out the binding helps ensure nothing is able to even try to modify the UI beyond this point, thus avoiding that whole class of issues. By not clearing the binding, there’s a potential for memory leaks or crashes in your app that are difficult to reproduce/debug
💯 3
m
Fragments can out live their view. Part of the goal of
onDestroyView
is to reduce memory usage by cleaning up all the views. If you keep a reference to the view binding, then the memory will not get cleaned up. At one of the Google IO events, they mentioned changing this behavior to destroy the fragment at the same time as the view because it was a common source of bugs. I don't know if they ever made that change.
f
@mkrussel this hasn't happened nor i think will happen since many apps will need to make breaking changes
i
It hasn't happened yet. It will be an opt in change when it is done later this year
👍 2
j
It is not just memory leak prone, but also crash prone 🙂 If you show a fragment, let's call it SomeFragment, it first creates the fragment and then the view within the fragment. If another fragment is shown in the same container, the SomeFragment is usually pushed to the backstack. The view within the fragment is destroyed, but the fragment object itself is still alive. This is to make it more convenient to not having to reinitialize everything, but still optimize resources (because views are very resource intensive). Then if the fragment is popped back from the stack, the view within the fragment gets recreated. Now if you do not re-initialize the view binding, the view binding will still reference the old view and you will get illegal state exceptions. Therefore, in onDestroyView, you should reset (nullify) the view binding. Luckily, there are solutions with propery delegations that observe the ViewLifecycle of a fragment, and bind when views get created and nullify the reference when destroyed. You can check articles on this, like: https://proandroiddev.com/make-android-view-binding-great-with-kotlin-b71dd9c87719 Then you don't have to do the lifecycle handling every time
👍 1
258 Views