Skip to content

Instantly share code, notes, and snippets.

@truedem
Last active October 3, 2024 09:30
Show Gist options
  • Save truedem/1ad60d166c8dcdac8225b7ff092a82d5 to your computer and use it in GitHub Desktop.
Save truedem/1ad60d166c8dcdac8225b7ff092a82d5 to your computer and use it in GitHub Desktop.
Delayed operation till resumed stage in Android activity and fragment
// usage:
// delayInResumed(10L) {
// binding.appBottomBar.updateTabs()
// }
fun Activity.delayInResumed(
durationMs: Long = 0,
dispatcher: CoroutineDispatcher = Dispatchers.Main,
block: () -> Unit
) {
delayInResumed(lifecycle, lifecycleScope, durationMs, dispatcher, block)
}
fun Fragment.delayInResumed(
durationMs: Long = 0,
dispatcher: CoroutineDispatcher = Dispatchers.Main,
block: () -> Unit
) {
delayInResumed(lifecycle, lifecycleScope, durationMs, dispatcher, block)
}
fun delayInResumed(
lifecycle: Lifecycle,
lifecycleScope: LifecycleCoroutineScope,
durationMs: Long,
dispatcher: CoroutineDispatcher = Dispatchers.Main,
block: () -> Unit
) {
val job = lifecycleScope.launch(dispatcher) {
delay(durationMs)
if (lifecycle.currentState.isAtLeast(Lifecycle.State.RESUMED)) {
block()
}
}
if (lifecycle.currentState.isAtLeast(Lifecycle.State.RESUMED)) {
job.start()
} else {
lifecycle.addObserver(object : LifecycleEventObserver {
override fun onStateChanged(source: LifecycleOwner, event: Lifecycle.Event) {
if (event == Lifecycle.Event.ON_RESUME) {
lifecycle.removeObserver(this)
job.start()
} else if (event == Lifecycle.Event.ON_DESTROY && job.isActive) {
job.cancel()
}
}
})
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment