Skip to content

Instantly share code, notes, and snippets.

@ArthurNagy
Last active May 4, 2021 04:46
Show Gist options
  • Save ArthurNagy/9fb1af79eddad4d0924f14d3f7131c56 to your computer and use it in GitHub Desktop.
Save ArthurNagy/9fb1af79eddad4d0924f14d3f7131c56 to your computer and use it in GitHub Desktop.
View Lifecycle owner
class MyCustomView @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0) :
View(context, attrs, defStyleAttr) {
private val viewModel = MyViewModel()
private val viewLifecycleOwner = ViewLifecycleOwner()
init {
viewModel.data.observe(viewLifecycleOwner) { data ->
// ...
}
}
override fun onAttachedToWindow() {
super.onAttachedToWindow()
viewLifecycleOwner.onAttachedToWindow()
}
override fun onDetachedFromWindow() {
super.onDetachedFromWindow()
viewLifecycleOwner.onDetachedFromWindow()
}
}
class ViewLifecycleOwner : LifecycleOwner {
private val lifecycleRegistry by lazy {
LifecycleRegistry(this).also {
it.handleLifecycleEvent(Lifecycle.Event.ON_START)
}
}
override fun getLifecycle(): Lifecycle = lifecycleRegistry
fun onAttachedToWindow() {
lifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_START)
}
fun onDetachedFromWindow() {
lifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_STOP)
}
}
@paramaggarwal
Copy link

Thank you for this.

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