Skip to content

Instantly share code, notes, and snippets.

@victory316
Created June 23, 2023 09:01
Show Gist options
  • Save victory316/3c77debc2bfc7d44e9849ab8ee88b923 to your computer and use it in GitHub Desktop.
Save victory316/3c77debc2bfc7d44e9849ab8ee88b923 to your computer and use it in GitHub Desktop.
Lifecycle aware extensions.
fun Activity.doOnceOnLifecycle(state: Lifecycle.State, action: () -> Unit) {
(this as? LifecycleOwner)?.lifecycleScope?.launch {
when (state) {
Lifecycle.State.CREATED -> withCreated {
action.invoke()
}
Lifecycle.State.STARTED -> withStarted {
action.invoke()
}
Lifecycle.State.RESUMED -> withResumed {
action.invoke()
}
else -> {
action.invoke()
}
}
}
}
fun Activity.doRepeatOnLifecycle(state: Lifecycle.State, action: () -> Unit) {
(this as? LifecycleOwner)?.lifecycleScope?.launch {
repeatOnLifecycle(state) {
action.invoke()
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment