Skip to content

Instantly share code, notes, and snippets.

@baggednismo
baggednismo / ViewLifecycleAware.kt
Created November 30, 2020 20:59 — forked from rishabhkohli/!!ViewLifecycleAware.kt
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