Skip to content

Instantly share code, notes, and snippets.

@samiuelson
Created September 4, 2018 15:34
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save samiuelson/74b13ec6083fb653cd4dbac36962ac03 to your computer and use it in GitHub Desktop.
Save samiuelson/74b13ec6083fb653cd4dbac36962ac03 to your computer and use it in GitHub Desktop.
Property delegate useful for Android development. Allows to declare lazily evaluated properties dependant on Activity Context and avoid memory leaks.
class LifecycleAwareLazy<T>(lifecycle: Lifecycle, private val initializer: () -> T) :
Lazy<T>, GenericLifecycleObserver {
init {
lifecycle.addObserver(this)
}
private object UNINITIALIZED_VALUE
private var _value: Any? = UNINITIALIZED_VALUE
@get:Synchronized
override val value: T
get() {
if (_value === UNINITIALIZED_VALUE) {
_value = initializer.invoke()
}
return _value as T
}
override fun isInitialized(): Boolean = _value != UNINITIALIZED_VALUE
// GenericLifecycleObserver
override fun onStateChanged(source: LifecycleOwner?,
event: Lifecycle.Event?) =
when (event) {
Lifecycle.Event.ON_STOP -> {
_value = UNINITIALIZED_VALUE
}
else -> Unit
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment