I want to create a coroutine method which has returning value.
For example)
fun funA() = async(CommonPool) {
return 1
}
fun funB() = async(CommonPool) {
return 2
}
fun sum() {
launch {
val total = funA().await() + funB().await()
}
}
If I want to return total in sum method, how should I do?
like,
fun sum(): Int {
launch {
val total = funA().await() + funB().await()
}
return total
}
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
}
}