Last active
May 4, 2021 04:46
-
-
Save ArthurNagy/9fb1af79eddad4d0924f14d3f7131c56 to your computer and use it in GitHub Desktop.
View Lifecycle owner
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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() | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thank you for this.