Why we need coroutine suspend modifier?


#1

Maybe it sounds stupid. But still I couldnt find any answer so far. I just jumped into coroutines few weeks ago and it is changing my point of view on async progrmaming. Thanks for that! To the point:

I wanted to test what I learned about coroutines. So I just took small android app and I rewrote some interfaces to use coroutines. Basically just add suspend modifier and use retrofit-coroutine library. Everywhere where I called such interface I used async builder and it worked.

Than I’ve wrapped location service and storage service. At one point I was thinking it is not probably a good way to have async everywhere, it looked more like Promise pattern than coroutines, so I just started to adding suspending functions to higher and higher interfaces and I ended up with one big launch builder around whole activity onCreate method and bunch of suspend function.

At that point I’ve started to asking myself why I need to mark functions as suspendable? As a user of an interface a use them in a same manner. No difference. Only If I want them run asynchronously i can use async. But I can have suspend modifier on actually non suspending function at all. Why not all the functions in kotlin are suspendable by default without modifier? Woudn’t it be easier for developers? Less code, less builders? Is it due to readability? Or some statical analysis? Performance? Or is there some “real” reason?

Hope it all make sense. Thank you for answer!

Ondrej


#2

Yes there is a reason :wink: You might not see it but the suspend keyword adds an additional parameter to your function. If you go and take a look at the bytecode or decompile it back to java you see that

suspend fun test() {}

actually is

fun test(continuation: Continuation) {}

This hidden parameter is used to make coroutines work. If you want to know how it works exactly you have to ask someone more knowledgable than me, but this is the reason why you have to use the suspend modifier.


#3

Thank you for answer. I see. But why not to add such parameter to all of the functions?


#4

For example, it will completely break java compatibility.
For now, calling suspended function from java is a pain. We do not want that for all functions. Also it is very useful to understand by looking on keywords, weather we are looking for the common code that could be run, say, from the UI thread, or suspended function that is long running and must be invoked on another thread.


#5

Great point! Thank you. Didn’t think about compatibility.