https://kotlinlang.org logo
#android
Title
# android
p

purna

06/19/2018, 11:10 AM
I was wondering which would be better declaration of a method
Copy code
suspend fun methodName(image: Bitmap?): String? = async {
   // heavy task
}.await()
OR
Copy code
fun methodName(image: Bitmap?): String? {
   //heavyTask
}
and in Code
Copy code
async{
   methodName()
}.await()
1
2️⃣ 1
1️⃣ 3
g

gildor

06/19/2018, 1:30 PM
It's more complicated question. Depends on what is "heavy task". If you mean "blocking heavy task" than both snippets are incorrect. You should not wrap blocking code to coroutine with default context (your code implicitly uses CommonPool), you should use some special IO context that safe to block and which works just like a thread pool. So wrapping blocking call would be something like:
Copy code
val IO = newFixedThreadPoolContext(POOL_SIZE, "IoDispatcher")

suspend fun methodName() = withContext (IO) {
//Heavy work
}
But don't forget that in many cases you cannot cancel "blocking heavy work", so be careful with this If "hevy work" is some async work, so do not blocking thread, just use suspend function without additional wrapper with custom context,
👍 2