Skip to content

Instantly share code, notes, and snippets.

@pandulapeter
Created April 17, 2019 13:21
Show Gist options
  • Save pandulapeter/23a4bf0399a2f6c831e83f0413a46967 to your computer and use it in GitHub Desktop.
Save pandulapeter/23a4bf0399a2f6c831e83f0413a46967 to your computer and use it in GitHub Desktop.
class AutoClearedValue<T : Any> : ReadWriteProperty<Fragment, T>, LifecycleObserver {
private var _value: T? = null
override fun getValue(thisRef: Fragment, property: KProperty<*>): T =
_value ?: throw IllegalStateException("Trying to call an auto-cleared value outside of the view lifecycle.")
override fun setValue(thisRef: Fragment, property: KProperty<*>, value: T) {
thisRef.viewLifecycleOwner.lifecycle.removeObserver(this)
_value = value
thisRef.viewLifecycleOwner.lifecycle.addObserver(this)
}
@OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
fun onDestroy() {
_value = null
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment