charlesmuchene
03/13/2020, 1:31 PMstreetsofboston
03/13/2020, 1:41 PMsuspend fun
is called.
A(nother) thread in the thread-pool that is defined in the Coroutine’s Dispatcher, is then executing the suspend fun
itself.
When that thread is done executing the suspend fun
, the calling thread resumes.
In the mean time, the calling thread may have been doing some other stuff.charlesmuchene
03/13/2020, 1:45 PMsuspend
is a like a cue to
Hey you Dispatcher threads. Work on this and let me know when you’re done?
streetsofboston
03/13/2020, 1:45 PMsuspend fun
from a Coroutine whose Dispatcher has only one thread (e.g the main ui thread), and somewhere in your code you block the code (e.g. Thread.sleep, waiting for a socket, etc), your code will still block, because there is no other thread in the thread-pool to serve that blocking thread and allow the calling thread to suspend.streetsofboston
03/13/2020, 1:46 PMsuspend fun
is like a callback:
suspend fun myFun(a: Int): String
== fun myFun(a: Int, continuation: Continuation<String>): Any
streetsofboston
03/13/2020, 1:48 PMmyFun
is done, the continuation
, which is a fancy callback, is called with the resulting String
callback value.
The difference is with suspend
, that your callback value is rewritten by the compiler to become a return value instead, allowing to write normal, imperative/sequential code instead of dealing with callbacks.Evan R.
03/13/2020, 1:51 PMContinuation
instance so when the suspending function returns the calling suspend function can be resumed from the point it left off.
4. The calling suspending function then stashes all its local variables in a state machine instance and the function is returned from. It is no longer running.
5. Eventually, the invoked suspending function will be dispatched from the dispatcher’s queue onto one of the threads it manages.
6. The suspending callee will eventually return and schedule the suspending caller using the continuation it received onto the dispatcher so the suspending caller can receive the return value.
7. The suspending caller eventually gets dispatched onto the thread pool again and resumes from where it left off, retrieving all its old state from its state machine.charlesmuchene
03/13/2020, 1:53 PMcharlesmuchene
03/13/2020, 1:54 PMLuis Munoz
03/13/2020, 3:11 PMEvan R.
03/13/2020, 3:13 PMLuis Munoz
03/13/2020, 3:13 PMLuis Munoz
03/13/2020, 3:13 PMLuis Munoz
03/13/2020, 3:13 PMEvan R.
03/13/2020, 3:13 PMLuis Munoz
03/13/2020, 3:14 PMEvan R.
03/13/2020, 3:18 PMEvan R.
03/13/2020, 3:18 PMEvan R.
03/13/2020, 3:19 PMLuis Munoz
03/13/2020, 3:22 PMLuis Munoz
03/13/2020, 3:23 PMEvan R.
03/13/2020, 3:33 PMEvan R.
03/13/2020, 3:34 PMEvan R.
03/13/2020, 4:03 PMRunnable
implementation which handles invoking the next task in the queue and parking until new coroutines come inEvan R.
03/13/2020, 4:05 PMEvan R.
03/13/2020, 4:06 PMcharlesmuchene
03/13/2020, 4:08 PM