Skip to content

Instantly share code, notes, and snippets.

@nimaiwalsh
Created August 12, 2021 23:27
Show Gist options
  • Save nimaiwalsh/3d9ffef7f2fd00272c6a78a3016d7c2e to your computer and use it in GitHub Desktop.
Save nimaiwalsh/3d9ffef7f2fd00272c6a78a3016d7c2e to your computer and use it in GitHub Desktop.
Safe delay in Android Views with Coroutines
/**
*
* Safely run some delayed tasks in a view as they will be tied to the lifecycle.
*
* @param durationInMillis delay task in millisecons
* @param dispatcher CoroutineDispatcher, defaults to Dispatchers.Main as view work is done on Main thread
* @param block the block of work to be done
*
* example:
*
* myView.delayOnLifeCycle(500L) {
* // Do something
* }
*
* */
fun View.delayOnLifecycle(
durationInMillis: Long,
dispatcher: CoroutineDispatcher = Dispatchers.Main,
block: () -> Unit
): Job? = findViewTreeLifecycleOwner()?.let { lifecycleOwner ->
lifecycleOwner.lifecycle.coroutineScope.launch(dispatcher) {
delay(durationInMillis)
block()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment