[Android] DataBinding-ktx 1.1.1: Fix memory leak and support LiveData

Takumi WADA
DataBinding-ktx
Published in
2 min readMar 22, 2019

DataBinding-ktx 2.0.0 has been released.

Original article is below.

What is DataBinding-ktx

A library that simplifies DataBinding variable declaration using Kotlin’s Delegated Properties. By using this library, you can declare properties as follows.

Library is here → https://github.com/wada811/DataBinding-ktx
For more information on how to use DataBinding-ktx, see below for how to use DataBinding-ktx.

Fixed memory leak in Fragment

I released DataBinding-ktx and published the above article, and received the following points from takahirom. Thank you 🙏

Since I spent so much as not to see the abyss of Fragment, I had completely forgotten to return from BackStack and regenerate View. The route of the arrow from onDestroyView to onCreateView in the figure below.

https://github.com/xxv/android-lifecycle

If you do not clear the binding variable in onDestroyView, memory leaks because binding is grabbing View. Therefore, I used AAC Lifecycle to clear the binding.

Here is the technical details of how to clear the binding variable. Fragment’s viewLifecycleOwner can only be used after onCreateView. Therefore, we observe onStart as follows and observe onDestroyView using viewLifecycleOwner with onStart.

thisRef.lifecycle.addObserver(object : LifecycleObserver {
@OnLifecycleEvent(Lifecycle.Event.ON_START)
fun onViewCreated() {
thisRef.lifecycle.removeObserver(this)
thisRef.viewLifecycleOwner.lifecycle.addObserver(object : LifecycleObserver {
@OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
fun onDestroyView() {
thisRef.viewLifecycleOwner.lifecycle.removeObserver(this)
binding = null
}
})
}
})

LiveData support

It is necessary to call the binding variable setLifecycleOwner when DataBinding of LiveData, but there was a voice that I forgot because I was addicted, so when I bind with DataBinding-ktx, I automatically call setLifecycleOwner.

Although Android has various addicts, let’s solve it with a mechanism without relying on human ability.

--

--