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
c

Cody Engel

04/28/2020, 8:47 PM
👋🏻 Hey everyone, I'm looking to create a
CoroutineScope
which I want to run in the background while it's waiting for updates to be sent via a Channel, but once the update is sent, I want the result to be executed on the main thread. In that case, would I want to use
Dispatchers.Main.immediate
, something like this
CoroutineScope(Dispatchers.Main.immediate + Job())
? I think I'm getting a little hung up as I'm not sure when I would have a Scope that doesn't use that dispatcher (since I can launch a suspending function with the scope, but telling it to switch to a different dispatcher, say
IO
).
z

Zach Klippenstein (he/him) [MOD]

04/28/2020, 8:54 PM
If you’re just calling
receive()
on a channel and waiting for a value to come in, you don’t need to use a special dispatcher for that. You can just receive from the channel on the main dispatcher.
o

octylFractal

04/28/2020, 8:55 PM
if you use
immediate
dispatcher it might dispatch immediately if the message is also posted from the main thread, but that can be dangerous. if the messages are only sent from non-main threads, then there's no reason to use
immediate
additionally, every scope implicitly has a
Job()
, you don't need to add one explicitly unless you prefer it that way 🙂
🙇‍♂️🏻 1
c

Cody Engel

04/28/2020, 9:10 PM
@Zach Klippenstein (he/him) [MOD] I think I may see what you're talking about, instead of having a custom scope it'd just be using
MainScope()
?
z

Zach Klippenstein (he/him) [MOD]

04/28/2020, 9:52 PM
Sure, that's one way to do it. The IO dispatcher is for blocking calls that block the current thread by not doing any work, but just sitting there waiting for the OS to return a value.
Channel.receive()
is a suspending call, which means it doesn't block the thread, and can thus be invoked from the main thread.
c

Cody Engel

04/28/2020, 10:11 PM
Yeah but
receive
can only be invoked from another suspending function so I need to use
CoroutineScope.launch
somewhere. So from the consumer side it's essentially this:
abstract class FooStatusConsumer(
    coroutineScope: CoroutineScope,
    channel: Channel<FooStatus> = Channel()
) {
    init {
        coroutineScope.launch(<http://Dispatchers.IO|Dispatchers.IO>) {
            for (fooStatus in channel) {
                withContext(Dispatchers.Main) {
                    consume(fooStatus)
                }
            }
        }
    }

    abstract fun consume(fooStatus: FooStatus)
}
o

octylFractal

04/28/2020, 10:15 PM
why not
Dispatchers.Main
at the top, drop
withContext
?
c

Cody Engel

04/28/2020, 10:18 PM
That's what I'm trying to figure out. My understanding is I'd want to switch to the IO dispatcher before I start IO work which I would think waiting for channel updates would warrant that. Before sending updates though I would want to ensure I'm doing so from Main which is why I have a second context
It appears to work without switching dispatchers though, so I'm guessing waiting for responses from a channel doesn't require switching to the IO dispatcher 🤷‍♂️🏻
o

octylFractal

04/28/2020, 10:33 PM
that's what zachklipp was getting at though -- suspend functions don't block threads
that's why it's an extremely useful concurrency model, because you don't have to switch your context whenever you do something that might be blocking -- if instead you know it will be suspending, you can stay in the same context but free up the thread while it waits
c

Cody Engel

04/28/2020, 10:37 PM
I getcha, for whatever reason your message made a bit more sense. So if it's just calling a suspend function, as long as you
launch
from a scope then you are good to go. I'm guessing if I wanted to kick off the suspend function from the IO or Default dispatcher that's when I'd use a scope which started with that... But in the majority of practical situations
MainScope()
is probably a decent place to start
Thanks Octavia and Zach 🙇🏻
o

octylFractal

04/28/2020, 10:38 PM
yes, usually I remain in one dispatcher for the most part, and only if I need to do something blocking do I
withContext(<http://Dispatchers.IO|Dispatchers.IO>)
-- whether that be the Main or Default dispatcher depends on which part of the code I'm in
z

Zach Klippenstein (he/him) [MOD]

04/28/2020, 10:51 PM
In fact, using the IO dispatcher just to receive from a channel could actually be slower, because if something is already in the channel then it has to jump to the IO pool’s queue, and then back into the main queue, instead of just pulling the next available item out immediately and starting to process it.
c

Cody Engel

04/29/2020, 1:37 PM
Awesome, thanks guys this makes so much more sense now 🙇🏻