Philosophical Question: Recently while talking abo...
# coroutines
p
Philosophical Question: Recently while talking about Coroutines with a colleague he asked what is
suspend
. My naive response was:
Copy code
Basically, if you declare a function `suspend`, when this function gets called, its actual invocation is placed in a Queue of Jobs to be executed in some Dispatcher. 
If the Dispatcher Thread happen to be the same as the calling Thread, it may be possible that the invocation happens immediately in the same running loop.
After the *suspending function* executes free of exceptions, then code will resume at the line right after the function call site.
Then he replied: What happened to the original Thread that called the
suspending function
. Then I said:
Copy code
The calling Dispatcher Thread returns at the calling site. When the *suspend function* is over the Continuation mechanics make sure it resumes in the same caller Dispatcher, not necessarily the same caller Thread but the same caller Dispatcher
Is anything terribly misleading in my brief summary of suspension?
s
Sometimes I explain it like this: A function marked with
suspend
is like using a callback; This function, in byte code, will have one extra parameter at the end that is basically a callback (in the form of a
Continuation
). It is somewhat like a
map
or
flatMap
(Rx) or
andThen
(Futures), where the code continues in the lambdas (callbacks) provided to those `map`/`flatMap`/`andThen` when the called function finally has a result. But this is different: Using callbacks, when the called function has a result, the callback’s code appears to the right side of the actual function call. Using
suspend
, the Continuation allows the written code, that is being called back, to appear to the left side of the actual functional call, being able to deal with a regular return-value instead of a callback (the compiler re-writes the code using a Continuation, in a type of callback style).
p
very nice, I like it. The analogy with RxJava is excellent to me, since that's the background of most people that I deal with. Its also good to explain
flow
. Thanks!
u
suspend is just sugar for the callback + allowing it participate in the "and then" chains
😸 1