Skip to content

Instantly share code, notes, and snippets.

@jossiwolf
Last active December 4, 2019 16:45
Show Gist options
  • Save jossiwolf/9682dda6fcb29de27b758397a9763b4f to your computer and use it in GitHub Desktop.
Save jossiwolf/9682dda6fcb29de27b758397a9763b4f to your computer and use it in GitHub Desktop.
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleObserver
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.OnLifecycleEvent
import kotlin.properties.ReadOnlyProperty
import kotlin.reflect.KProperty
/**
* Proxy for [LifecycleAwareLazyImpl]
* @see LifecycleAwareLazyImpl
*/
fun <T> lifecycleAwareLazy(lifecycle: Lifecycle, initialiser: () -> T) = LifecycleAwareLazyImpl(lifecycle, initialiser)
/**
* Proxy for [LifecycleAwareLazyImpl] - enables direct usage in LifecycleOwner objects
* @sample ```private val layoutManager by lifecycleAwareLazy { MyLayoutManager() }```
* @see LifecycleAwareLazyImpl
*/
fun <T> LifecycleOwner.lifecycleAwareLazy(initialiser: () -> T) = LifecycleAwareLazyImpl(lifecycle, initialiser)
/**
* Lifecycle-Aware (naive) lazy implementation
* Destroys the value when [Lifecycle.Event.ON_PAUSE] is called and recreates it with the given [initialiser] once re-requested
* @param lifecycle The lifecycle of the object to watch
* @param initialiser The function called to obtain the [T] instance
*
* @sample ```private val layoutManager by LifecycleAwareLazy(this.lifecycle) { MyLayoutManager() }```
*/
class LifecycleAwareLazyImpl<T>(
lifecycle: Lifecycle,
private val initialiser: () -> T
) : ReadOnlyProperty<LifecycleOwner, T>, LifecycleObserver {
private var value: T? = null
init {
lifecycle.addObserver(this)
}
operator fun setValue(thisRef: Any, property: KProperty<*>, value: T) {
throw IllegalStateException("Cannot set value on a ReadOnlyProperty")
}
override operator fun getValue(thisRef: LifecycleOwner, property: KProperty<*>): T {
if (value == null) {
value = initialiser()
}
return value!!
}
@Suppress
@OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)
fun pause() {
value = null
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment