Created
September 4, 2018 15:34
-
-
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.
This file contains hidden or 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
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