ViewLifecycleLazy and other ways to avoid View memory leaks in Android Fragments

Yet another take on AutoClearedValue

A leaky pipe symbolizing a memory leak
Are your Fragments leaking?
class MyFragment : Fragment(R.layout.my_fragment) {
private val binding by viewLifecycleLazy(MyFragmentBinding::bind)
}

Why it’s simpler

The original code adds some unnecessary complexity by observing viewLifecycleOwnerLiveData, then in turn registering a new lifecycle observer on the new viewLifecycleOwner when it becomes available. It turns out this is not needed because the viewLifecycleOwner lifecycle observer can just be registered lazily, at the same time the value is initialized.

Why it generates more optimized bytecode

The original code is a classic property delegate, an object implementing the ReadOnlyProperty interface which includes this function:

abstract operator fun getValue(thisRef: T, property: KProperty<*>): V
inline operator fun <T> Lazy<T>.getValue(thisRef: Any?, property: KProperty<*>): T = value

Final advice: only use it if you have to

A meme of Kayode Ewumi grinning and pointing to his temple, with the caption: Can’t get a memory leak if you don’t have a property
class MyFragment : Fragment(R.layout.fragment_example) {
private val myViewModel: MyViewModel by viewModels()

override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
val viewHolder = ViewHolder(view)

initNavigationView(viewHolder.navigationView)

val adapter = MyAdapter()
viewHolder.recyclerView.adapter = adapter
myViewModel.result.observe(viewLifecycleOwner) { result ->
viewHolder.titleTextView.text = result.title
adapter.submitList(result.list)
}
}

private fun initNavigationView(navigationView: NavigationView) {
// TODO
}
}
interface RecycledViewPoolProvider {
val recycledViewPool: RecyclerView.RecycledViewPool
}
class ParentFragment : Fragment(R.layout.fragment_parent), RecycledViewPoolProvider {
override val recycledViewPool by viewLifecycleLazy {
RecyclerView.RecycledViewPool()
}
}

--

--

Android developer from Belgium, blogging about advanced programming topics.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Christophe Beyls

Android developer from Belgium, blogging about advanced programming topics.