I need to make some function in UI thread but after delay. I need the delay to not block the main thread. Fox example I have function makeSmthInMainThread() which I want to call in main thread after delay.
Here is my code:
GlobalScope.launch {
delay(3000)
makeSmthInMainThread()
}
Can you please tell me in this case the function will be executed in the main thread? Or do I need to wrap it in withContext(Dispatchers.Main) ?
Perhaps in this case it is better to use Handler() and postDelayed ?
Please, help me.
You need to use
launch(Dispatchers.Main)orwithContext(Dispatchers.Main)to execute the function in the Main Thread. By defaultGlobalScope.launchruns in a Worker Thread. But be careful,GlobalScopeis a delicate API, please read the docs before using it, it can create resource and memory leaks. Consider usingviewModelScopeproperty inViewModelclass orlifecycleScopeproperty inActivity/Fragmentto launch coroutines.