Created
June 23, 2023 09:01
-
-
Save victory316/3c77debc2bfc7d44e9849ab8ee88b923 to your computer and use it in GitHub Desktop.
Lifecycle aware extensions.
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
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