Skip to content

Instantly share code, notes, and snippets.

@diefferson
Last active October 18, 2019 17:13
Show Gist options
  • Select an option

  • Save diefferson/d33dfe5c17def1e9c93f4bfc752e3f4f to your computer and use it in GitHub Desktop.

Select an option

Save diefferson/d33dfe5c17def1e9c93f4bfc752e3f4f to your computer and use it in GitHub Desktop.
Lifecycle Safe delegate
class Activity:AppCompatActivity{
val actionsAdapter:MyListAdapter by lifecycleSafe(this){
MyListAdapter()
}
}
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