Last active
October 3, 2024 09:30
-
-
Save truedem/1ad60d166c8dcdac8225b7ff092a82d5 to your computer and use it in GitHub Desktop.
Delayed operation till resumed stage in Android activity and fragment
This file contains hidden or 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
// 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