Skip to content

Instantly share code, notes, and snippets.

@frel
Last active May 29, 2024 10:44
Show Gist options
  • Save frel/5f3f928c27f4106ffd420a3d99c8037c to your computer and use it in GitHub Desktop.
Save frel/5f3f928c27f4106ffd420a3d99c8037c to your computer and use it in GitHub Desktop.
/*
* Based on https://gist.github.com/jamiesanson/d1a3ed0910cd605e928572ce245bafc4
*
* Refactored to use the preferred `DefaultLifecycleObserver` which does not rely on the annotation processor.
* See https://developer.android.com/reference/kotlin/androidx/lifecycle/Lifecycle#init
*
* Usage:
* `private var binding: TheViewBinding by viewLifecycle()`
*/
/**
* An extension to bind and unbind a value based on the view lifecycle of a Fragment.
* The binding will be unbound in onDestroyView.
*
* @throws IllegalStateException If the getter is invoked before the binding is set,
* or after onDestroyView an exception is thrown.
*/
fun <T> Fragment.viewLifecycle(): ReadWriteProperty<Fragment, T> =
object : ReadWriteProperty<Fragment, T>, DefaultLifecycleObserver {
private var binding: T? = null
init {
// Observe the view lifecycle of the Fragment.
// The view lifecycle owner is null before onCreateView and after onDestroyView.
// The observer is automatically removed after the onDestroy event.
this@viewLifecycle
.viewLifecycleOwnerLiveData
.observe(this@viewLifecycle, Observer { owner: LifecycleOwner? ->
owner?.lifecycle?.addObserver(this)
})
}
override fun onDestroy(owner: LifecycleOwner) {
binding = null
}
override fun getValue(
thisRef: Fragment,
property: KProperty<*>
): T {
return this.binding ?: error("Called before onCreateView or after onDestroyView.")
}
override fun setValue(
thisRef: Fragment,
property: KProperty<*>,
value: T
) {
this.binding = value
}
}
@fahadadnan-01
Copy link

Thanks frel, I really appretiate it.

@AbGhost-cyber
Copy link

thanks frel

@brighthr-stanton
Copy link

Nice - thanks :)

@Ajayk1234
Copy link

Hi @frel. This is good. Can you please add instrumentation tests for this if you have time? It will be really helpful.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment