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
d

dave08

10/18/2018, 2:21 PM
Where to
supervisorScope { }
and
coroutineScope { }
get their
CoroutineScope
from?
m

marstran

10/18/2018, 2:23 PM
They create one. That's their purpose.
d

dave08

10/18/2018, 2:24 PM
In the kdocs it says
The provided scope inherits its [coroutineContext][CoroutineScope.coroutineContext] from the outer scope, but overrides context's [Job] with [SupervisorJob].
...?
If I don't have an outer
CoroutineScope
does it automatically inherit the
GlobalScope
? Also does it have any default Dispatcher?
s

SiebelsTim

10/18/2018, 2:28 PM
It inherits the context, not the scope. You can get the context from any suspend function
👍🏼 1
d

dave08

10/18/2018, 2:31 PM
So
from the outer scope
in the kdocs, is really just an assumption that we are running from one, otherwise, it could be a
runBlocking
or
GlobalScope
... so it gets cancelled along with wherever the suspend function was called from, right?
s

SiebelsTim

10/18/2018, 2:54 PM
I'm not sure I can follow.
coroutineScope
is a
suspend fun
, therefore it can only be called from a suspending function. Every suspending functions has an implicit Continuation and therefore a
CoroutineContext
. This
CoroutineContext
is used. So when you are using
coroutineScope {}
within a coroutine that was launched on
GlobalScope
, the new scope will inherit `GlobalScope`'s context.
👍🏼 1
d

dave08

10/18/2018, 2:59 PM
Oh, sorry, now I got it! I guess I thought only the Dispatcher was getting passed along... but you're right, the whole context, including the current Job + Dispatcher (which is a child of any outer
CoroutineScope
the
suspend fun
is being called from). Thanks a lot, this is now much clearer!
🙂 1
v

Vsevolod Tolstopyatov [JB]

10/18/2018, 3:19 PM
As it was correctly mentioned, these builders inherit
coroutineContext
, not the scope.
CoroutineScope
is a wrapper around
coroutineContext
, which is created by builders. It does not matter whether you have outer scope or not, because
coroutineContext
is always present in suspend functions.
Also does it have any default Dispatcher?
No. Which dispatcher is used depends on particular primitive. E.g. for most of our builders (
async
,
launch
,
produce
etc.)
Dispatchers.Default
will be used if context does not have one.
d

dave08

10/18/2018, 3:28 PM
That could be a bit confusing... the same
launch
called from a suspend function could be
Dispatchers.Default
or inherit a parent's dispatcher far back in the call stack... so if one would call it from
runBlocking
or
GlobalScope
it would work on
Dispatchers.Default
but from a presenter running on
Dispatchers.Main
inheriting from the Presenter's
CoroutineScope
..., shouldn't this be a bit more explicit? @Vsevolod Tolstopyatov [JB]
v

Vsevolod Tolstopyatov [JB]

10/18/2018, 3:55 PM
or inherit a parent’s dispatcher far back in the call stack...
It cannot happen “out of thin air”. You have precise control over what happens: 1) You can use
coroutineScope
. Then you are using convention “here is my isolated scope with dispatcher inherited from the caller”. 2) You can make your method extension on coroutine scope. Then again you are opt-in for “caller is responsible” 3) You can use
withContext(dispatcher)
, then you are forcing dispatcher you want 4) Your API requires dispatcher in parameters and/or you are always pass it explicitly such as
fun CoroutineScope.launchInIO = async(IO) { ... }
shouldn’t this be a bit more explicit
We are always open for a better proposals 🙂 But explicitly requiring dispatcher in every builder is too verbose. The idea of structured concurrency is that once you have a scope, all coroutines inherit it and optionally override some parts of context.
d

dave08

10/18/2018, 4:05 PM
Thanks for the explanation, #1 is the one I'm concerned about, say for an api that handles some computation in parallel, the api provider expects the default
Dispatchers.Default
to be used like it used to be before structured concurrency.. or someone migrating to structured concurrency might not notice that instead of defaulting to something similar to
CommonPool
it gets inherited from the scope ... which could be completely wrong... maybe some kind of migration guide or stress in the docs along with a link to it from the release notes (that I assume is usually what most people look at...).
Or maybe even better... to allow to override the Dispatcher in the
coroutineScope
and
supervisorScope
builders as if one used
withContext
?
That way, the entry point doesn't make any assumptions, but has the option to be explicit without having to specify it for each
launch
or
async
...
That's really what I was expecting when I first approached this new api...
v

Vsevolod Tolstopyatov [JB]

10/18/2018, 4:53 PM
to allow to override the Dispatcher in the
coroutineScope
withContext(dispatcher)
🙂
the api provider expects the default
Dispatchers.Default
That way, the entry point doesn’t make any assumptions
if you expect it — specify it explicitly. Nothing in API prevents you from that. You can use
withContext(Dispatcher)
or create
CoroutineScope(coroutineContext + dispatcher)
and use it as receiver etc.
I don’t understand what you are trying to achieve or what pieces you miss. API is rich and allows you to enforce almost any behaviour you like. If you are itself an API provider you have a various options to enforce context you want. If you are writing concrete business logic you may have an implicit contract “everything executes in UI thread by default” and use it. But what we can’t do is to protect users from every possible API misuse 🙂
Though I understand that the library is quite large and most of the primitives are new. I’m thinking about making a F.A.Q. with short answers for most common questions like “What’s the difference between coroutineContext and CoroutineScope?“. The trick is not to make another
coroutine-guide.md
🙂 I’d happy to have your questions in this F.A.Q if you’ll make them short and concrete
d

dave08

10/18/2018, 7:20 PM
My use case is a component that downloads multiple files in parallel, and each file is downloaded in parts in parallel (saved to different numbered files). The code is spread out in a few classes to make it pluggable and to offer different options. I need to
launch
(parts) and
async
(file received) and
produce
(for download progress) spread out in all those classes. It comes out that I have a few `coroutineScope`s spread out all over, those are internal, so they can inherit a dispatcher. But the entrypoints need to be explicit, so if there would be
coroutineScope(<http://Dispatchers.IO|Dispatchers.IO>) { }
for those endpoints, anyone using this library even from the main thread would be fine, and to the implementor it's clearer and more explicit than
coroutineScope { withContext(<http://Dispatchers.IO|Dispatchers.IO>) { } }
. Both forms are needed, no?
I once thought it would be nice to have a best practices guide with examples on recommended common use patterns, I think that would be even more useful than a faq. When it comes to using coroutines in practise, there's the do's and the don'ts...
The guide is for explaining basic concepts, the best practises are more like short guidelines in a point form with short examples or links to samples...