When to use Kotlin suspend keyword?
suspend
keyword means coroutine can be suspended for later execution.
Having said that, you should consciously use it them for coroutines that will get suspended (e.q. your asyncFunc2()
made a HTTP call and is awaiting response to process it)
So.
- Use
suspend
for functions that will be delayed in some way (Awaiting some computations, api response etc.) suspend fun
can be run from coroutine only. So, if it gets suspended, it will block the coroutine. Take out thesuspend
keyword, but run it in coroutine and it will have the same effect. However, if you run this function from outside the coroutine, it will block the thread it was running on.
When testing coroutines, you should always invoke runBlocking
. If you don't, a coroutine that gets suspended may not complete, resulting in a failed test.
You should only declare your function suspend
if it needs to. If the compiler does not force you, don't use suspend
.
One possible exception to this rule would be if you're defining this function as an open method (for instance in an interface) and you expect that some implementations/overrides will need to call suspending functions themselves.
Most of the time, if you have a good reason for your function to be suspending, it means it's probably doing something that requires you to call suspending functions anyway. For instance, you might use withContext
to switch to a particular thread pool, or you might wrap a callback-based function using suspendCancellableCoroutine
. Either way, calling those functions would force you to add the suspend
modifier to your function.
Also, note that declaring a function suspend
does not enable your callers to do anything more than they could when your function was not suspending. If anything, you're limiting the use of your function.