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

diesieben07

12/31/2018, 5:40 PM
I am still not quite sure when I should be using
fun foo(): Deferred<Foo>
vs.
suspend fun foo(): Foo
. The code must execute on a specific dispatcher, so I could use
withContext
for the
suspend
version. It feels to me like
suspend
is the cleaner variant. Correct?
d

dave08

12/31/2018, 6:01 PM
Yes, but you might want that class to receive a CoroutineContext in its constructor just in case you need to switch it for testing or something. Deferred is usually when you run it with
async {}
and only need the result later
Also, it's better to keep it suspend and use async at calling site, so you can opt in to concurrency, or use it without when needed. Also the scope you run from is usually at the top level (like in the ui or viewmodel/presenter), and you generally need one for async anyways
d

Dico

12/31/2018, 6:10 PM
Consider making it an extension function of
CoroutineScope
Or use suspend version
Also, I think
withContext
has little cost when the thread is already the target
d

dave08

12/31/2018, 6:12 PM
The extension function isn't so nice if its not in the same class... since there's two receivers you need a
with
on one of them
But this is all only for blocking api, to wrap callbacks all this isn't usually needed of course...
s

Sam

12/31/2018, 7:36 PM
@dave08 is switching the context for testing to make launched coroutines as blocking?
d

dave08

12/31/2018, 8:48 PM
There's Dispatchers.Unconfined or you can turn something running on a thread pool to run on a singlr thread instead. You still need to test concurrency, bit you can simplify things when its not needed.
That's one of the reasons I find it better to write everything in repositories etc as simple suspends without concurrency (or at least with a replaceable context), and have real concurrency in the main class with the context, it makes testing simple in all the other classes @Sam
s

Sam

12/31/2018, 8:52 PM
Okay, in my case i'm using Unconfined. I was actually hoping to avoid calling .join() from runBlocking in my test
override fun onButtonClicked() = viewModelScope.launch {
        doSomething() // suspend function
    }
viewModelScope is built using the dispatcher passed via constructor (Main in case of application and Unconfined in case of tests)
In tests, i have
runBlocking {
            viewModel.onButtonClicked().join()
            verify( ...)
        }
Is there a way to avoid this join?
d

dave08

12/31/2018, 8:55 PM
Can you pass runBlocking's scope? That should block the viewmodelscope...
s

Sam

12/31/2018, 8:55 PM
I thought of doing that but in a sample it didn't work as expected
runBlocking {

        val dispatcher1 : CoroutineDispatcher = coroutineContext[ContinuationInterceptor] as CoroutineDispatcher

        launch(dispatcher1) {

            delay( 1000 )
            println( "first finished" )
        }

        println( "outer finished" )

    }
in this case, even though the dispatcher is passed to launch builder, outer finished is processed on delay
d

dave08

12/31/2018, 8:56 PM
The
it
in runBlocking is its scope...
If you create your viewmodel instance inside it, you can technically just pass
it
as the scope, no?
s

Sam

12/31/2018, 8:59 PM
Okay, instead of a dispatcher, i could pass in an entire scope
but even then, isn't that the same as this?
runBlocking {

        launch {

            delay( 1000 )
            println( "first finished" )
        }

        println( "outer finished" )

    }
d

dave08

12/31/2018, 9:01 PM
In that case, you need to use runBlocking scope + another dispatcher like io
That way you get the join automatically, but it runs the launch async
And the coroutines get cancelled with their runBlocking parent
Or just leave the scope in the viewmodel and use its job to join to runBlocking and cancel at the end...
Maybe even make a little extension function to reuse in all your tests for this
s

Sam

12/31/2018, 9:05 PM
I didn't get the IO dispatcher part, it still doesn't change the behavior
runBlocking {

        val scope = CoroutineScope( coroutineContext + <http://Dispatchers.IO|Dispatchers.IO> )

        scope.launch {

            delay( 1000 )
            println( "first finished" )
        }

        println( "outer finished" )

    }
Am i missing something?
waiting on the launched coroutine with join() in runBlocking does work. It just forces a Job return type on my view model methods. I was hoping to avoid that.
d

dave08

12/31/2018, 9:10 PM
Basically I believe you need to use runBlocking's Job in the new scope, then the launch will become its child... I'm not sure why that shouldn't work... maybe use
it
instead of
coroutineContext
? I can't test it out i'm not on a computer now 🙂
s

Sam

12/31/2018, 9:13 PM
no worries. Actually, runBlocking gets a this, which is a coroutinecontext
Tried getting the job from coroutinecontext and used that to build the scope but still the same behavior
I guess my problem statement, is there a way to enforce sequential execution of all child coroutines from a runBlocking
g

groostav

12/31/2018, 11:35 PM
regarding the original question @vnsgbt I think this is actually one of kotlins masterstrokes: always use `suspend `if you can, because it keeps everything sequential by default, which is probably the best way to start writing concurrent systems. I was just recently burned by a couple
public async Task doStuff()
in C#, where I forgot to
await
the return value because its effectively void
, and I got the resulting typical concurrent heisenbugs.
The strategy in kotlin of just "lets assume its synchronous" is a good one, but that strategy only really helps if you use
suspend fun asdf(): R
by default instead of
fun asdfAsync(): SomeJobType<R>
as your default way of thinking
d

diesieben07

01/01/2019, 12:21 PM
Wow, you go on a party for new years and you come back to this, thanks guys, I'll read the thread now 😄
😁 1
@groostav That makes sense and it does indeed produce the cleanest code.
suspend
it is.
d

dave08

01/01/2019, 12:26 PM
Roman spoke about this a bit in the recent webinar on coroutines @diesieben07
d

diesieben07

01/01/2019, 12:26 PM
Thanks, I was meaning to check that out. Thank you for reminding me