Skip to content

Instantly share code, notes, and snippets.

@trevorhackman
Created December 11, 2021 23:24
Show Gist options
  • Save trevorhackman/5720777cccf79ea9c09dae8a3c1cc578 to your computer and use it in GitHub Desktop.
Save trevorhackman/5720777cccf79ea9c09dae8a3c1cc578 to your computer and use it in GitHub Desktop.
For nulling something on destroy, primary motivation, a better way to do view binding.
/**
* Delegate for use in fragments
*
* When the fragment's view is destroyed the field will be set to null.
* This happens immediately before the fragment's onDestroyView() is called.
*
* Additionally, this delegate gives the same behavior as lateinit.
*
* Property should be a non-nullable var.
*/
fun <T : Any> Fragment.nullOnDestroy(): NullOnDestroy<T> = NullOnDestroy(this)
class NullOnDestroy<T : Any>(
fragment: Fragment
) : ReadWriteProperty<Fragment, T>, LifecycleObserver {
private var value: T? = null
init {
fragment.viewLifecycleOwnerLiveData.observeForever {
it?.lifecycle?.addObserver(this)
}
}
@OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
fun onDestroy() {
value = null
}
override fun getValue(thisRef: Fragment, property: KProperty<*>): T {
return value ?: throw IllegalStateException("Property ${property.name} should be initialized before get.")
}
override fun setValue(thisRef: Fragment, property: KProperty<*>, value: T) {
this.value = value
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment