When to use Kotlin suspend keyword?

As a general rule of thumb, you should only declare your function suspend if the compiler forces you to.

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.

It’s important to note that both suspension and cancellation are cooperative in the coroutines world. This means that marking a function suspend doesn’t do anything on its own. If you don’t call suspending functions inside it, or check the cancellation status manually, it probably does more harm than good to mark it as suspend (because the machinery has a cost but you get no benefit from it in this case).

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.

Leave a Comment

tech