https://kotlinlang.org logo
Channels
100daysofcode
100daysofkotlin
100daysofkotlin-2021
advent-of-code
aem
ai
alexa
algeria
algolialibraries
amsterdam
android
android-architecture
android-databinding
android-studio
androidgithubprojects
androidthings
androidx
androidx-xprocessing
anime
anko
announcements
apollo-kotlin
appintro
arabic
argentina
arkenv
arksemdevteam
armenia
arrow
arrow-contributors
arrow-meta
ass
atlanta
atm17
atrium
austin
australia
austria
awesome-kotlin
ballast
bangladesh
barcelona
bayarea
bazel
beepiz-libraries
belgium
benchmarks
berlin
big-data
books
boston
brazil
brikk
budapest
build
build-tools
bulgaria
bydgoszcz
cambodia
canada
carrat
carrat-dev
carrat-feed
chicago
chile
china
chucker
cincinnati-user-group
cli
clikt
cloudfoundry
cn
cobalt
code-coverage
codeforces
codemash-precompiler
codereview
codingame
codingconventions
coimbatore
collaborations
colombia
colorado
communities
competitive-programming
competitivecoding
compiler
compose
compose-android
compose-desktop
compose-hiring
compose-ios
compose-mp
compose-ui-showcase
compose-wear
compose-web
confetti
connect-audit-events
corda
cork
coroutines
couchbase
coursera
croatia
cryptography
cscenter-course-2016
cucumber-bdd
cyprus
czech
dagger
data2viz
databinding
datascience
dckotlin
debugging
decompose
decouple
denmark
deprecated
detekt
detekt-hint
dev-core
dfw
docs-revamped
dokka
domain-driven-design
doodle
dsl
dublin
dutch
eap
eclipse
ecuador
edinburgh
education
effective-kotlin
effectivekotlin
emacs
embedded-kotlin
estatik
event21-community-content
events
exposed
failgood
fb-internal-demo
feed
firebase
flow
fluid-libraries
forkhandles
forum
fosdem
fp-in-kotlin
framework-elide
freenode
french
fritz2
fuchsia
functional
funktionale
gamedev
ge-kotlin
general-advice
georgia
geospatial
german-lang
getting-started
github-workflows-kt
glance
godot-kotlin
google-io
gradle
graphic
graphkool
graphql
graphql-kotlin
graviton-browser
greece
grpc
gsoc
gui
hackathons
hacktoberfest
hamburg
hamkrest
helios
helsinki
hexagon
hibernate
hikari-cp
hire-me
hiring
hongkong
hoplite
http4k
hungary
hyderabad
image-processing
india
indonesia
inkremental
intellij
intellij-plugins
intellij-tricks
internships
introduce-yourself
io
ios
iran
israel
istanbulcoders
italian
jackson-kotlin
jadx
japanese
jasync-sql
java-to-kotlin-refactoring
javadevelopers
javafx
javalin
javascript
jdbi
jhipster-kotlin
jobsworldwide
jpa
jshdq
juul-libraries
jvm-ir-backend-feedback
jxadapter
k2-early-adopters
kaal
kafka
kakao
kalasim
kapt
karachi
karg
karlsruhe
kash_shell
kaskade
kbuild
kdbc
kgen-doc-tools
kgraphql
kinta
klaxon
klock
kloudformation
kmdc
kmm-español
kmongo
knbt
knote
koalaql
koans
kobalt
kobweb
kodein
kodex
kohesive
koin
koin-dev
komapper
kondor-json
kong
kontent
kontributors
korau
korean
korge
korim
korio
korlibs
korte
kotest
kotest-contributors
kotless
kotlick
kotlin-asia
kotlin-beam
kotlin-by-example
kotlin-csv
kotlin-data-storage
kotlin-foundation
kotlin-fuel
kotlin-in-action
kotlin-inject
kotlin-latam
kotlin-logging
kotlin-multiplatform-contest
kotlin-mumbai
kotlin-native
kotlin-pakistan
kotlin-plugin
kotlin-pune
kotlin-roadmap
kotlin-samples
kotlin-sap
kotlin-serbia
kotlin-spark
kotlin-szeged
kotlin-website
kotlinacademy
kotlinbot
kotlinconf
kotlindl
kotlinforbeginners
kotlingforbeginners
kotlinlondon
kotlinmad
kotlinprogrammers
kotlinsu
kotlintest
kotlintest-devs
kotlintlv
kotlinultimatechallenge
kotlinx-datetime
kotlinx-files
kotlinx-html
kotrix
kotson
kovenant
kprompt
kraph
krawler
kroto-plus
ksp
ktcc
ktfmt
ktlint
ktor
ktp
kubed
kug-leads
kug-torino
kvision
kweb
lambdaworld_cadiz
lanark
language-evolution
language-proposals
latvia
leakcanary
leedskotlinusergroup
lets-have-fun
libgdx
libkgd
library-development
lincheck
linkeddata
lithuania
london
losangeles
lottie
love
lychee
macedonia
machinelearningbawas
madrid
malaysia
mathematics
meetkotlin
memes
meta
metro-detroit
mexico
miami
micronaut
minnesota
minutest
mirror
mockk
moko
moldova
monsterpuzzle
montreal
moonbean
morocco
motionlayout
mpapt
mu
multiplatform
mumbai
munich
mvikotlin
mvrx
myndocs-oauth2-server
naming
navigation-architecture-component
nepal
new-mexico
new-zealand
newname
nigeria
nodejs
norway
npm-publish
nyc
oceania
ohio-kotlin-users
oldenburg
oolong
opensource
orbit-mvi
osgi
otpisani
package-search
pakistan
panamá
pattern-matching
pbandk
pdx
peru
philippines
phoenix
pinoy
pocketgitclient
polish
popkorn
portugal
practical-functional-programming
proguard
prozis-android-backup
pyhsikal
python
python-contributors
quasar
random
re
react
reaktive
realm
realworldkotlin
reductor
reduks
redux
redux-kotlin
refactoring-to-kotlin
reflect
refreshversions
reports
result
rethink
revolver
rhein-main
rocksdb
romania
room
rpi-pico
rsocket
russian
russian_feed
russian-kotlinasfirst
rx
rxjava
san-diego
science
scotland
scrcast
scrimage
script
scripting
seattle
serialization
server
sg-user-group
singapore
skia-wasm-interop-temp
skrape-it
slovak
snake
sofl-user-group
southafrica
spacemacs
spain
spanish
speaking
spek
spin
splitties
spotify-mobius
spring
spring-security
squarelibraries
stackoverflow
stacks
stayhungrystayfoolish
stdlib
stlouis
strife-discord-lib
strikt
students
stuttgart
sudan
swagger-gradle-codegen
swarm
sweden
swing
swiss-user-group
switzerland
talking-kotlin
tallinn
tampa
teamcity
tegal
tempe
tensorflow
terminal
test
testing
testtestest
texas
tgbotapi
thailand
tornadofx
touchlab-tools
training
tricity-kotlin-user-group
trójmiasto
truth
tunisia
turkey
turkiye
twitter-feed
uae
udacityindia
uk
ukrainian
uniflow
unkonf
uruguay
utah
uuid
vancouver
vankotlin
vertx
videos
vienna
vietnam
vim
vkug
vuejs
web-mpp
webassembly
webrtc
wimix_sentry
wwdc
zircon
Powered by
Title
i

Ive Vasiljevic

12/04/2019, 1:22 PM
fun 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()?
d

diesieben07

12/04/2019, 1:25 PM
runBlocking
, 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 tasks
👍 2
l

Luke Sleeman

12/04/2019, 10:36 PM
That's a really good explanation! It brings up a bit of a broader question for me though: I've been trying hard to develop a mental model for coroutines. It seems they are kind of like threads, but not quite, but perhaps executed on a thread 🤷 I'm also having a lot of trouble imagining how they are actually implemented. Is it safer to imagine coroutines as an event loop, where you can enque new tasks via
launch
? 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?
o

octylFractal

12/04/2019, 10:39 PM
https://github.com/Kotlin/KEEP/blob/master/proposals/coroutines.md#coroutines-overview it does not have to be an event loop (many dispatchers use a thread pool), scopes are not queues (that is strictly part of the Dispatcher's internal implementation), but rather a way to inherit properties from the parent jobs (structured concurrency)
l

Luis Munoz

12/04/2019, 10:47 PM
in a thread pool you submit tasks that executed, in an event loop you submit tasks that get executed. conceptually they are similar. usually in an event loop you should never block. in a thread pool you can block a thread and it is fine. looking at coroutine code to me it looks like it uses a thread pool to queue tasks which are made of coroutine sections. meaning it takes a suspend function and splits it into section at suspension points and those sections are queued in thread pools.
o

octylFractal

12/04/2019, 10:49 PM
whether it is a thread pool or event queue is dependent on the dispatcher: Default/IO are pools, Main is usually an event loop,
runBlocking
is an event loop
Dispatchers.UNDISPATCHED is a little special, I don't think it is either a pool or a loop (runs on the thread that resumes, whatever it is)
d

Dico

12/05/2019, 3:18 AM
Coroutines can be broken down as follows: 1. Suspension points are syntactic sugar for using callbacks. 2. Context provides a way to control the executor/scheduling and an inheritance structure among coroutines. Here, a coroutine is a sequence (imperative, not concurrent) of tasks. Only when you introduce more than 1 coroutine, is when it becomes concurrent.
l

Luke Sleeman

12/05/2019, 3:19 AM
🤔 🤔 that's interesting. Can you elaborate on what you mean by
Suspension points are syntactic sugar for using callbacks.
?
u

ursus

12/05/2019, 7:01 AM
Imagine it how it actually is = nested callbacks, i.e. sequences of "and then.." actions, just the level of indentation if sugared away
b

bezrukov

12/05/2019, 7:20 AM
Actually under the hood it works a bit different. It's state machine where suspension points are states. You can watch Deep dive into Coroutines by Roman Elizarov for more details.
e

Evan R.

12/05/2019, 2:23 PM
Re-posting, fixing the attachments… Here’s the talk that @bezrukov mentioned:

https://www.youtube.com/watch?v=YrrUCSi72E8

There’s also a really good one from the GOTO conference where Roman gives a visual representation of how coroutines work and compares them to other ways of doing async:

https://youtu.be/hQrFfwT1IMo

If you’re interested, here’s the way I visualize coroutines: 1. Dispatchers - schedulers which take coroutines off a queue and run them on backing thread pools. Examples are
Dispatchers.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.
d

Dico

12/06/2019, 12:25 PM
I was trying to simplify 😅
I think the materials linked here can clarify how they act like callbacks
l

Luke Sleeman

12/09/2019, 12:36 AM
Thanks, this is really helpful stuff! I'm definitely going to sit down and watch those two videos.