If I understand your question correctly, you want to create a function ex. "doWork()" that does work on a coroutine and returns the result of that work directly and concisely being able to update your UI without freezing it.
Thus, based on the above:
First, I would totally avoid using runBlocking , as it will block the UI thread or main thread eventually till 'doWork()' finishes its work on whatever other thread you specify.
I find the most appropriate solution to achieve your goal is by using Koltin Flow as you will be able to publish the progress later on if you want to in the future.
Here's how:
fun doWork(): Flow<Int> =
flow {
//do long work
val sum:Int = doCalculations()
emit(sum)
}.flowOn(Dispatchers.Default)
The flow will run on a coroutine by default.
And in your view you call this function:
launch(Dispatchers.Main){
doWork().single{
val my result=it
//Update your UI
}
}
Another simpler solution:
Make doWork() a suspend function
suspend fun doWork(): Int =
withContext(Dispatchers.Default){
//do long work
val sum:Int = doCalculations()
return@withContext sum
}
And in your view you call this function:
launch(Dispatchers.Main){
val my result=doWork()
//Update your UI
}
}
funA().await() + funB().await()you are actually runningfunA()andfunB()sequentially. If you want to run them in parallel, you should doval a = funA(), andval b = funB(), and then doa.await() + b.await().await. The value of these two variables will be an unresolved promise, which is why you need the await.sumshould call it inside a coroutine instead of turning asynchronous code into synchronous, which defeats the purpose of coroutines. You would have to block the caller offun sum. If your caller is synchronous, then I would think this is the problem, and your question is searching for a band aid for the symptom, not the cause.