-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
[email protected](this) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Important to note that LifecycleObserver is found in "androidx.lifecycle:lifecycle-common-java8:$version"