Ive Vasiljevic
12/04/2019, 1:22 PMfun main() = runBlocking {
val job = launch {
println("Coroutine start")
launch {
println("Child coroutine start")
println("Child coroutine end")
launch {
println("Child-inner coroutine start")
println("Child-inner coroutine end")
}
}
println("Coroutine end")
println("Coroutine end!")
}
println("Join")
println("Done")
}
Why is Join and Done executed before job? And when calling job.join() between println("Join") and println("Done") job is executed at the place of calling job.join()?diesieben07
12/04/2019, 1:25 PMrunBlocking
, is an event loop. It executes tasks one by one. The first task is the lambda you pass to runBlocking
, it is executed completely ("Join" and "Done" happen). Then it starts to execute the other tasks in the queue one by one (job is the first one).
If you .join on the job, the lambda passed to runBlocking
is split into two tasks: first part until .join and 2nd part after. In between it is suspended and the event loop executes other tasksLuke Sleeman
12/04/2019, 10:36 PMlaunch
? Scopes are different queues? Dispatchers allow you to run queues on different threads? functions like join
, yeild
and delay
alow you to split your function into separate tasks?
Is this an accurate mental model of coroutines? Is this somewhat similar to how they are actually implemented behind the scenes?octylFractal
12/04/2019, 10:39 PMLuis Munoz
12/04/2019, 10:47 PMoctylFractal
12/04/2019, 10:49 PMrunBlocking
is an event loopDico
12/05/2019, 3:18 AMLuke Sleeman
12/05/2019, 3:19 AMSuspension points are syntactic sugar for using callbacks.
?ursus
12/05/2019, 7:01 AMbezrukov
12/05/2019, 7:20 AMEvan R.
12/05/2019, 2:23 PMDispatchers.Default
and <http://Dispatchers.IO|Dispatchers.IO>
2. Coroutine context - Collection of elements which make up a coroutine, such as a Job
which handles cancellation and the Dispatcher
which schedules coroutines
3. Coroutine scope - a logical block which launches sibling coroutines and cancels others if a failure occurs. Launching within this scope queues jobs to the dispatcher, which will eventually run them on the backing thread pool
4. Suspending function - a function which can immediately exit (suspend) and give control back to a dispatcher’s worker thread when another suspending function is invoked. What really happens when you invoke another suspending function is you queue the next suspending function call on the dispatcher, immediately exit the function, then when the other suspend function is done you pick back up where you left off.
Where suspending functions really shine is the fact that you can use withContext
to launch a job on a separate thread pool and your current thread pool won’t be blocked by the other job.
And yes, it is safe to think of the Dispatcher as an event loop because it kind of is one.Dico
12/06/2019, 12:25 PMLuke Sleeman
12/09/2019, 12:36 AM