Skip to content

Instantly share code, notes, and snippets.

@baggednismo
Forked from rishabhkohli/!!ViewLifecycleAware.kt
Created November 30, 2020 20:59
Show Gist options
  • Save baggednismo/a2b15010e2757cbe657aa71b6d99f178 to your computer and use it in GitHub Desktop.
Save baggednismo/a2b15010e2757cbe657aa71b6d99f178 to your computer and use it in GitHub Desktop.
A Kotlin delegated property implementation which automatically clears itself at appropriate times in the View Lifecycle of a Fragment.
import androidx.fragment.app.Fragment
import androidx.lifecycle.DefaultLifecycleObserver
import androidx.lifecycle.LifecycleOwner
import kotlin.properties.ReadOnlyProperty
import kotlin.reflect.KProperty
fun <T> Fragment.viewLifecycleAware(initialise: () -> T): ReadOnlyProperty<Fragment, T> =
object : ReadOnlyProperty<Fragment, T>, DefaultLifecycleObserver {
private var binding: T? = null
override fun onDestroy(owner: LifecycleOwner) {
binding = null
}
override fun getValue(thisRef: Fragment, property: KProperty<*>): T =
binding
?: initialise().also {
binding = it
this@viewLifecycleAware.viewLifecycleOwner.lifecycle.addObserver(this)
}
}
@baggednismo
Copy link
Author

Important to note that LifecycleObserver is found in "androidx.lifecycle:lifecycle-common-java8:$version"

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment