Skip to content

Instantly share code, notes, and snippets.

@ThomasGorisse
Created October 19, 2021 19:51
Show Gist options
  • Save ThomasGorisse/62fadaec4b7715673f2acb36fe99df39 to your computer and use it in GitHub Desktop.
Save ThomasGorisse/62fadaec4b7715673f2acb36fe99df39 to your computer and use it in GitHub Desktop.
val View.lifecycleOwner: LifecycleOwner
get() = getTag(R.id.view_lifecycle_owner) as? LifecycleOwner ?: object : LifecycleOwner,
LifecycleEventObserver {
private val lifecycle = LifecycleRegistry(this)
init {
doOnAttach {
findViewTreeLifecycleOwner()?.lifecycle?.addObserver(this)
}
doOnDetach {
findViewTreeLifecycleOwner()?.lifecycle?.removeObserver(this)
lifecycle.currentState = Lifecycle.State.DESTROYED
}
}
override fun onStateChanged(source: LifecycleOwner, event: Lifecycle.Event) {
lifecycle.currentState = event.targetState
}
override fun getLifecycle(): Lifecycle {
return lifecycle
}
}.also {
setTag(R.id.view_lifecycle_owner, it)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment