Created
August 12, 2021 23:27
-
-
Save nimaiwalsh/3d9ffef7f2fd00272c6a78a3016d7c2e to your computer and use it in GitHub Desktop.
Safe delay in Android Views with Coroutines
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
/** | |
* | |
* 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