Last active
October 18, 2019 17:13
-
-
Save diefferson/d33dfe5c17def1e9c93f4bfc752e3f4f to your computer and use it in GitHub Desktop.
Lifecycle Safe delegate
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 Activity:AppCompatActivity{ | |
| val actionsAdapter:MyListAdapter by lifecycleSafe(this){ | |
| MyListAdapter() | |
| } | |
| } |
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 lifecycleSafe<T>(lifecycleOwner: LifecycleOwner,val initValue :()-> T) : LifecycleObserver { | |
| private var value: T? = null | |
| init { | |
| lifecycleOwner.lifecycle.addObserver(this) | |
| } | |
| @OnLifecycleEvent(Lifecycle.Event.ON_CREATE) | |
| fun create() { | |
| value = initValue() | |
| } | |
| @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY) | |
| fun destroy() { | |
| value = null | |
| } | |
| operator fun setValue(thisRef: Fragment, property: KProperty<*>, value: T) { | |
| throw IllegalStateException("Cannot set value on a ReadOnlyProperty") | |
| } | |
| operator fun getValue(thisRef: Fragment, property: KProperty<*>): T { | |
| return value!! | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment