Skip to content

Instantly share code, notes, and snippets.

@frel
Last active April 18, 2023 11:25
Show Gist options
  • Star 10 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • 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

hi should this part of the code be changed from this
.observe(this@viewLifecycle
to
.observe(this@viewLifecycle.viewLifecycleOwner

I am just a bit confused

@frel
Copy link
Author

frel commented Jun 4, 2020

Hi @markchristopherng

.observe(this@viewLifecycle
to
.observe(this@viewLifecycle.viewLifecycleOwner

To clarify:
this@viewLifecycle is just a qualified scope to tell the compiler to use the scope of Fragment.viewLifecycle in this case. I.e. since this is an extension function on fragmentthis@viewLifecycle is the fragment (which also happens to be a LifecycleOwner).
this would here be scoped to the instance of object : ReadWriteProperty<Fragment, T>, DefaultLifecycleObserver { ... } e.g. allowing to accessthis.binding

viewLifecycleOwnerLiveData is a LiveData of the lifecycle of the fragment view not the fragment instance. As views can be created, destroyed and recreated while the fragment is created. (onCreateView/onDestroyView can be called multiple times in pairs after onCreate). As the comment mentiones, before onCreateView is called the viewLifecycleOwner will be null.

As mentioned this@viewLifecycle is the fragment (which is also a LifecycleOwner) and it will automatically remove the Observer of the viewLifecycle when the owner moves to the DESTROYED state.

I hope that cleared things up, if not please ask :)

@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