Hard to grasp coroutine explanation
See original GitHub issueI would like to provide some feedback on the learning materials which are used to explain coroutines.
Here is a code example from the coroutine guide:
fun main(args: Array<String>) = runBlocking<Unit> {
val job = launch { // launch new coroutine and keep a reference to its Job
delay(1000L)
println("World!")
}
println("Hello,")
job.join() // wait until child coroutine completes
}
This code launches a coroutine, than waits for it to complete. I had a lot of trouble with this code when I learned coroutines, and now I understand why.
The (mental) problem is that it is not made clear where the actual blocking is happening. Does launch {...}
blocks anything or not? If not, then why is it inside runBlocking {...}
?
The answer to that is this code is excessive. Here is a version which helped me to understand what is going on:
fun main(args: Array<String>) {
val job = launch { // launch new coroutine and keep a reference to its Job
delay(1000L)
println("World!")
}
println("Hello,")
runBlocking<Unit> {
job.join() // wait until child coroutine completes
}
}
Here we 1) launch a coroutine 2) wait for it. This was much clearer to me. Ideally I would even prefer it to be like job.joinBlocking()
, so it looks like threads even more.
I understand that your version is more idiomatic, easier to work with, etc, but I think that new learners need that extra step to understand the concept.
Issue Analytics
- State:
- Created 6 years ago
- Reactions:1
- Comments:6 (3 by maintainers)
Top GitHub Comments
I rewrote the corresponding section in the guide in
develop
branch based on your suggestions. Take a look, please: https://github.com/Kotlin/kotlinx.coroutines/blob/develop/coroutines-guide.md#bridging-blocking-and-non-blocking-worldsThe result is the same, but this code uses only non-blocking delay. The the main thread, that invokes runBlocking, blocks until the coroutine inside runBlocking is active.
One small thing that bugged me… I would say until the coroutine inside is started, runned and completed