Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Andrej1A/a2fe491174cfcc47036644551a8a9bb8 to your computer and use it in GitHub Desktop.
Save Andrej1A/a2fe491174cfcc47036644551a8a9bb8 to your computer and use it in GitHub Desktop.
Kotlin Property Delegate for Fragment view lifecycle binding
fun <T> Fragment.viewLifecycle(bindUntilEvent: Lifecycle.Event = Lifecycle.Event.ON_DESTROY): ReadWriteProperty<Fragment, T> =
object: ReadWriteProperty<Fragment, T>, LifecycleObserver {
// A backing property to hold our value
private var binding: T? = null
private var viewLifecycleOwner: LifecycleOwner? = null
init {
// Observe the View Lifecycle of the Fragment
this@viewLifecycle
.viewLifecycleOwnerLiveData
.observe(this@viewLifecycle, Observer { newLifecycleOwner ->
viewLifecycleOwner
?.lifecycle
?.removeObserver(this)
viewLifecycleOwner = newLifecycleOwner.also {
it.lifecycle.addObserver(this)
}
})
}
@OnLifecycleEvent(Lifecycle.Event.ON_ANY)
fun onDestroy(event: Lifecycle.Event) {
if (event == bindUntilEvent) {
// Clear out backing property just before onDestroyView
binding = null
}
}
override fun getValue(
thisRef: Fragment,
property: KProperty<*>
): T {
// Return the backing property if it's set
return this.binding!!
}
override fun setValue(
thisRef: Fragment,
property: KProperty<*>,
value: T
) {
// Set the backing property
this.binding = value
}
}
}
override fun setValue(thisRef: Any, property: KProperty<*>, value: T) {
this.property = value
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment