Skip to content

Instantly share code, notes, and snippets.

@cbeyls
Created September 18, 2022 20:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cbeyls/4c627cc2a313d3d7887a328846d4d5d2 to your computer and use it in GitHub Desktop.
Save cbeyls/4c627cc2a313d3d7887a328846d4d5d2 to your computer and use it in GitHub Desktop.
A lazy property that gets cleaned up when the fragment's view is destroyed
package be.digitalia.common.fragment
import android.view.View
import androidx.fragment.app.Fragment
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleEventObserver
import androidx.lifecycle.LifecycleOwner
/**
* A lazy property that gets cleaned up when the fragment's view is destroyed.
*
* Accessing this variable while the fragment's view is destroyed will throw NPE.
*/
fun <T : Any> Fragment.viewLifecycleLazy(initializer: (View) -> T): Lazy<T> =
ViewLifecycleLazy(this, initializer)
private class ViewLifecycleLazy<out T : Any>(
private val fragment: Fragment,
private val initializer: (View) -> T
) : Lazy<T>, LifecycleEventObserver {
private var cached: T? = null
override val value: T
get() {
return cached ?: run {
val newValue = initializer(fragment.requireView())
cached = newValue
fragment.viewLifecycleOwner.lifecycle.addObserver(this)
newValue
}
}
override fun isInitialized() = cached != null
override fun toString() = cached.toString()
override fun onStateChanged(source: LifecycleOwner, event: Lifecycle.Event) {
if (event == Lifecycle.Event.ON_DESTROY) {
cached = null
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment