Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mark function suspend or using builder

I'm starting with coroutines in Android app. I'm rewriting callbacks to suspendCoroutine<> {} and I've got one dillema: when should I just mark the function as suspend, and when should I wrap the call in some builder (launch, async, etc.)?

Is there some best practice, rule of thumb, or something?

like image 1000
Pitel Avatar asked Aug 14 '26 20:08

Pitel


1 Answers

You should write a suspend fun for every asynchronous, callback-based API call you're currently making.

You should wrap in withContext(myThreadPool) every synchronous API call you're making.

All Android-friendly APIs that do I/O use the async approach, so for these you'll be writing suspend funs, but for CPU-intensive tasks (such as decoding images) you may need withContext.

Finally, to be able to use either kind of calls, you must create a top-level coroutine with launch(UI).


Keep in mind that the above is really just a rule of thumb. When you factor your code, many times you realize you need, for example, a suspend fun to make a CPU-intensive operation because there's a withContext somewhere on that call path.

Let me also add a warning about a very typical misuse of the coroutine APIs: you almost never need async-await. Use it only for the cases where you want to truly run it "in the background" while you continue to perform other stuff in your current context. In simpler terms, you should never write

val result = async { calculation() }.await()

Instead you should write

val result = withContext(myThreadPool) { calculation() }
like image 142
Marko Topolnik Avatar answered Aug 17 '26 13:08

Marko Topolnik



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!