Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it necessary to set ViewBinding to null in Fragment's onDestroy()?

Is it necessary to set ViewBinding to null in Fragment's onDestroy()? Sometimes I see that thing in tutorials. Is it really necessary?

like image 625
Viktor Avatar asked Feb 09 '21 12:02

Viktor


Video Answer


2 Answers

It is necessary and a really good practice, specially in Android where memory restrictions are huge, you really need to take care of cleaning up resources as and when you are done with them. ViewBinding will generate a custom ViewBinding class which will keep references to all your views inside Fragment, if ViewBinding is not cleared or set to null, it won't be eligible for GC, thereby holding all the views in memory even though you are not using it, leading to memory leaks. So yes, it is always better to set it to null at the end of life cycle.

like image 153
Rajan Kali Avatar answered Oct 20 '22 16:10

Rajan Kali


Yes it is recommended to set ViewBinding to null in onDestroyView.

ViewBinding is scoped to the lifecycle of the fragment's view (between onCreateView and onDestroyView). i.e. it is is only valid between onCreateView and onDestroyView.

Hence, please set the respective ViewBinding to null in fragment's onDestroyView.

like image 5
SVK Avatar answered Oct 20 '22 15:10

SVK