Created
April 17, 2019 13:21
-
-
Save pandulapeter/23a4bf0399a2f6c831e83f0413a46967 to your computer and use it in GitHub Desktop.
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 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