Below is my use case. I have a function fun requestFocus this function in turn call function fun configure which depends on a callback from system hence this function configure uses coundownlatch with count 1 and await until it is reset to zero when callback is received. For this I have marked requestFocus suspend and use Dispatchers.IO to do all its operation. Now there are multiple caller of requestFocus for ex function fun accept. The function accept does many things and all of them happens on same thread. function accept can also be called from main thread or intent service as well. My problem is since function configure is blocking I do not want to block main thread. Currently accept function looks like this
fun accept() { //do something requestFocus() // do something } I am not sure how I can call requestFocus from accept and have all the operation that happens post requestFocus execution to happen in same way. What I have done currently in accept function is below
fun accept() { //do something runBlocking{ requestFocus() // do something } But this creates problem as main thread gets blocked. Any suggestion what can I try? I have looked into documentation of Global scope and main scope.
runBlockingexcept in a unit test. It otherwise completely defeats the purpose of coroutines. UselifecycleScope.launchto start a coroutine. This is sort of like posting a Runnable to the main thread, but the code within the lambda can suspend and therefore callsuspendfunctions. So ifaccept()represents a complete flow of logic, usefun accept() = lifecycleScope.launch { /*...*/ }.