Venkat
05/21/2023, 4:52 PMhfhbd
05/21/2023, 5:43 PMVenkat
05/21/2023, 5:46 PMhfhbd
05/21/2023, 5:52 PMAdam S
05/21/2023, 6:53 PMsuspend
keyword basically does three things:
1. it adds an extra parameter to the function (a Continuation) which contains the coroutine context (so the current coroutine dispatcher/name/job is accessible)
2. whenever a suspend function is called the Kotlin compiler ✨magically✨ (using the Continuation) converts the code following invocation of a suspend function to a lambda, which will be called when the suspend function completes (this is what’s really clever about coroutines, because it helps prevent callback hell / heavy nesting - everything appears to be flat and in sequential)
3. and some machinery to allow for the Continuation to be suspended/resumed/cancelled, depending on the current state of the coroutine context
(this is just my layman’s understanding)
And this is all built into Kotiln. kotlinx.coroutines adds some excellent helpers and tools, but it’s only expanding upon the building blocks from Kotlin.
So if a function (be it a C interop function, or a regular Kotlin function) doesn’t have the suspend
keyword then it’s not going to get these under-the-hood changes, so it will just be called sequentially, like a regular function.hfhbd
05/21/2023, 6:58 PMAdam S
05/21/2023, 7:04 PM