Are coroutines just syntactic sugar around completion blocks and completion blocks will be created under the hood? Or is the concept of coroutines much more complex and broad then just compiler trick aka syntactic sugar
It's not just syntactic sugar, not at all. Coroutines do not block threads, they just suspend execution, thus they encourage non-blocking concurrent programming.
Coroutines do not rely on features of the operating system or the JVM (e.g. they are not mapped to native Threads). Instead, coroutines and suspend
functions particularly are transformed by the compiler producing a state machine capable of handling suspensions in general and passing around suspending coroutines keeping their state. This is enabled by Continuations, which are added as a parameter to each and every suspending function by the compiler; this technique is called “Continuation-passing style”.
For details please have a look at https://github.com/Kotlin/kotlin-coroutines/blob/master/kotlin-coroutines-informal.md
No, coroutines are not syntactic sugar. You can think of coroutines as of functions that can interact with the caller. When you call a normal function, say foo
you pass control to foo
and have to wait until foo
either completes or throws exception. Coroutines are functions which can pass control back to caller, and caller can decide whether coroutine should continue and when and how coroutine should continue. This gives opportunity to implement things which are special language constructs in other languages:
yield
keyword) like in C# and JavaScript. Caller continues execution of coroutine when a user wants new value from iterator. Coroutine passes back to caller by calling yield()
function, which also passes some value to caller.await()
function. Caller passes value to coroutine when Future gets resolved and coroutine observes this value as a result of await()
call.Unlike C#, JavaScript or Go, Kotlin does not implement any of these features in special syntax. Instead, Kotlin provides only suspend fun
syntax, and then you can implement these features yourself (or get existing one from corresponding library called kotlinx.coroutines
).
Corutines are syntactic sugar around asyncronous procedures, or, better say, Actors, which are repeatable asynchronous procedures.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With