https://kotlinlang.org logo
Title
r

Rick

11/26/2019, 7:01 AM
hi! i am new to kotlin's coroutines. i am confused now when a coroutine will suspend. manually call delay() wiil help but it seem to be too low level. can dispatcher know when a coroutine is blocking and suspend it itself
o

octylFractal

11/26/2019, 7:05 AM
no, suspension only happens when calling a suspend function
blocking will never suspend, because those are incompatible concepts
r

Rick

11/26/2019, 7:22 AM
it seems very clear. but when we need to define a function with a "suspend". in golang a goroutine will be suspended when it is call blocking syscall. what k's coroutine do?
what is the very inner suspend fn look like . is there blocking call?
o

octylFractal

11/26/2019, 7:47 AM
no, suspension is not blocking at all
https://github.com/Kotlin/KEEP/blob/master/proposals/coroutines.md#coroutines-overview is good reading for understanding how it works internally
in short though, every time you hit a
suspend
point, kotlin saves all the state to a Continuation, and then that Continuation is held by some code to be resumed later. While the coroutine is in such state, it is suspended and does not reside on any thread, because it can be resumed using information contained only in the Continuation, without any need for a stack frame to be retained
the difference to blocking being that blocking code must stay on a thread
r

Rick

11/26/2019, 8:53 AM
i have read all you mention above. k's coroutine seems to be a solution which dispatch code snippet into threads. it never handle block but avoiding block by put the heavy jobs to other io threads then keep the frontend thread in light. just like rx/reactor do
o

octylFractal

11/26/2019, 8:54 AM
correct. it's modeled this way because on the JVM side it can't change the threading model to a coroutine-style, so it has no control over blocking code
r

Rick

11/26/2019, 9:04 AM
ok. thank you a lot!