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
}
}
@markchristopherng
Copy link

Thanks for the explanation. This code is better than the original supplied by the author of the medium article.

@fahadadnan-01
Copy link

fahadadnan-01 commented Jul 10, 2020

in onDestroy why didn't you have the line

        super.onDestroy(owner)

I was wondering because the original author made a new implmentation
https://gist.github.com/jamiesanson/478997780eb6ca93361df311058dc5c2
where he did that.

Thanks

@frel
Copy link
Author

frel commented Jul 12, 2020

in onDestroy why didn't you have the line

        super.onDestroy(owner)

Because DefaultLifecycleObserver is an interface, albeit with default (empty) implementations to reduce boiler plate (you don't have to implement all the methods in FullLifecycleObserver. Thus calling super.onDestroy does nothing.

@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