https://kotlinlang.org logo
Docs
Join the conversationJoin Slack
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
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
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
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 Linen
coroutines
  • p

    pdegand

    10/25/2018, 9:17 AM
    afaik, the problem the problem is because the scoped used during the mocking is now different than the one used for the real call, therefor, the Continuation used is different. But I don't know how i can work around this problem.
    m
    d
    • 3
    • 4
  • l

    louiscad

    10/25/2018, 9:49 AM
    :kotlin: +😒uspend: + :android: Hi Android developers that use coroutines, I made a PR to kotlinx.coroutines for integration with AndroidX Lifecycle. If you think you can make a quality review on it, please do! Here it is: https://github.com/Kotlin/kotlinx.coroutines/pull/760
    🆒 4
    c
    • 2
    • 1
  • j

    Joris PZ

    10/25/2018, 1:48 PM
    I'm building a library that uses co-routines and channels internally. As I see it, I have a number of options when designing my public API: • Offer an API that exposes suspending functions (which in turn uses the internal Channel structure) • Hide my co-routines completely, and offer a blocking API to the clients • Provide two separate API classes (
    class XYZ
    and
    class BlockingXYZ
    ?) • Provide a single API class with both suspending and blocking versions of my methods, i.e.
    suspend fun doABC()
    and
    fun doABCBlocking()
    Are any of these choices considered idiomatic? Or should I just do what feels right to me?
    a
    • 2
    • 3
  • b

    bootstraponline

    10/25/2018, 2:49 PM
    is runBlocking supported on iOS? I have a simple example that hangs forever on iOS. JVM works fine. https://github.com/bootstraponline/run_blocking
    t
    • 2
    • 3
  • m

    Martin Devillers

    10/25/2018, 4:52 PM
    Is this expected? This test fails:
    @Test
    fun test() = runBlocking {
        assertTrue(actor<Unit> { for (it in this) {  } }.offer(Unit))
    }
    But this test passes:
    @Test
    fun test() = runBlocking {
        val actor = GlobalScope.actor<Unit> { for (it in this) {  } }
        delay(100)
        assertTrue(actor.offer(Unit))
    }
    It’s like the actor’s queue needs some time to be set up. It’s not ready right away after creation.
    e
    z
    • 3
    • 2
  • m

    Martin Devillers

    10/25/2018, 4:55 PM
    The fix is to use
    start = CoroutineStart.UNDISPATCHED
    , but that feels a bit weird
    e
    • 2
    • 19
  • d

    dave08

    10/25/2018, 5:43 PM
    I have a setup like this (just made it much simpler...), but it hangs... I tried different types of channels... conflated and all, how could I get this to work?
    import kotlinx.coroutines.experimental.channels.Channel
    import kotlinx.coroutines.experimental.channels.actor
    import kotlinx.coroutines.experimental.channels.consumeEach
    import kotlinx.coroutines.experimental.runBlocking
    import kotlinx.coroutines.experimental.*
    
    fun main(args: Array<String>) = runBlocking {
    	val progressNotifier = actor<Long>(<http://Dispatchers.IO|Dispatchers.IO>) {
    		consumeEach {
    			println(it.toString())
    		}
    	}
    
    	val progressMapper = actor<Int>(<http://Dispatchers.IO|Dispatchers.IO>) {
    		for (it in channel) {
    			progressNotifier.offer(it.toLong())
    		}
    	}
    
    	(0..5).forEach {
    		progressMapper.offer(it)
    	}
    
    	progressMapper.close()
    }
    a
    • 2
    • 5
  • i

    itnoles

    10/25/2018, 11:10 PM
    Some how, I get this JS Errors when I am trying to test it. > Uncaught ReferenceError: CoroutineImpl is not defined
    b
    • 2
    • 1
  • u

    uhe

    10/26/2018, 9:53 AM
    Am I the only one who can't set proper breakpoints in a lot of suspending functions? It just shows them as inactive even though the code is definitely being executed. Using AS 3.2.1 with Kotlin 1.2.71 and Coroutines 0.30.2
    v
    • 2
    • 2
  • s

    sindrenm

    10/26/2018, 11:28 AM
    Does anyone know why it would be a problem using both kotlinx.coroutines.experimental and kotlinx.coroutines (non-experimental) in the same project? Or rather, have one library that uses the experimental coroutines (with Kotlin 1.2) and in the app that consumes the library use the stable coroutines (and thus Kotlin 1.3, of course). Our app crashes when the library attempts to then refer to something from the experimental coroutines library:
    java.lang.NoClassDefFoundError: Failed resolution of: Lkotlinx/coroutines/experimental/BuildersKt;
    b
    e
    • 3
    • 13
  • z

    zjuhasz

    10/26/2018, 1:02 PM
    Right now there is only a Main dispatcher for GUI frameworks as far as I know. Has there been any discussion of always having a Main dispatcher? It's a really effective pattern (particularly when using coroutines) to only have one thread, even for non-ui applications. It allows you to completely forget about any thread safety problems in all cases except when there is some heavy cpu bound tasks that need to be parralelised. It also looks like the concept of always having a central thread is now baked into kotlin/native. In a vanilla jvm or native app
    suspend fun main()
    could start a single threaded dispatcher which would be the main dispatcher. You can make your own single threaded dispatcher for applications but it's a problem for libraries. Libraries can't safely use
    Dispatchers.Main
    because there is no gaurentee there will be an implementation in a users application. A library developer could require there to be an implementation of Dispatcher.Main meaning that if the user wasn't making a UI app they would have to provide their own implementation, but that seems to go against the docs. Also the documentation doesn't even say the main dispatcher must be single threaded, so it couldn't really be used as a home for operations that aren't thread safe anyway.
    e
    • 2
    • 4
  • j

    Jonathan

    10/26/2018, 3:35 PM
    Since
    suspend fun foo(): Int
    should be preferred to
    fun foo(): Deferred<Int>
    . Wouldn't it be nice if the IDE would show warning when the result of a function is a deferred? It could help newcomers.
    e
    • 2
    • 1
  • n

    Nikky

    10/26/2018, 5:21 PM
    i am trying to convert some ugly old code to use coroutines
    • 1
    • 1
  • m

    mp

    10/26/2018, 6:50 PM
    I'm on coroutines 0.25.0 (I'm on ktor 0.9.5, because the 1.0-betas are broken for me) and I need to launch a coroutine in a request handler that will run in the background after the request completes for a while. Naturally the current docs are all about the updated coroutines API -- is plain old
    launch {}
    what I want in 0.25.0 to make a coroutine that runs entirely disconnected from the coroutine executing the request handling logic?
    d
    • 2
    • 3
  • d

    darkmoon_uk

    10/27/2018, 7:14 AM
    Bit of an outsider question about the state-of-play with Coroutines: I enjoy using RxJava a lot in my UI designs, but also want to keep the code as portable as possible. Is there any effort, yet, to provide an 'RxJava equivalent' library based on coroutines, which I can use to trivially port my business logic away from RxJava, so that it can be compiled by Kotlin Native?
    g
    • 2
    • 4
  • f

    Felix

    10/27/2018, 1:51 PM
    From a "memory model" viewpoint (https://en.wikipedia.org/wiki/Java_memory_model) , I'm correct in assuming coroutines always ensure an "happens-before" order for actions between suspension points in the same coroutine, even if the actions run on different threads, right?
    g
    e
    • 3
    • 3
  • g

    groostav

    10/29/2018, 2:12 AM
    oh here's a funny question: whats the closest thing C# has to a
    kotlinx..Channel
    ?
    d
    • 2
    • 1
  • l

    louiscad

    10/29/2018, 9:39 AM
    🎉
    :yes: 4
    🍾 9
    🎉 9
    v
    d
    +3
    • 6
    • 10
  • s

    Sangeet

    10/29/2018, 11:09 AM
    I am facing one issue regarding coroutines. I am using
    CoroutineExceptionHandler
    to catch exception that is written inside a function. While calling that function again it is actually throwing previous Exception without executing any coroutines inside that. Can anybody help me with this.
    m
    • 2
    • 6
  • d

    dave08

    10/29/2018, 12:34 PM
    Ok, I think I got it,
    coroutineScope
    doesn't return until it completes... but then, I'd need to pass the CoroutineScope in
    download(scope: CoroutineScope)
    ? That's a bit messy... and I can't even use a receiver since it's declared on another object... (unless I use
    with
    ... 😒)
    m
    j
    n
    • 4
    • 19
  • d

    dekans

    10/29/2018, 4:27 PM
    Migration done!
    👍 6
    u
    • 2
    • 2
  • j

    jcechace

    10/29/2018, 4:56 PM
    I’m trying to understand coroutines scopes. So at top level I need a runBlocking function (e.g. main). Now if I have a another suspending function which uses async. Do I have to wrap the
    async
    calls into
    coroutineScope {}
    to inherit the coroutine scope from the calling function (e.g. main)?
    l
    d
    • 3
    • 6
  • s

    Steven McLaughlin

    10/29/2018, 6:03 PM
    I have a (probably naive) question regarding coroutines. Since 1.3 is out and coroutines are no longer experimental, do I still need to add the kotlinx-coroutines-core bit in my gradle file if I want to write something simple like
    runBlocking {
                things.forEach {
                    launch {
                        doTheThing(it)
                    }
                }
            }
    I wasn't sure if that was part of the base language now or not. I think I'm just a little confused about where the lines are drawn for this
    r
    • 2
    • 2
  • b

    bdawg.io

    10/29/2018, 6:22 PM
    After upgrading from Kotlin 1.2.71, coroutines 0.30.2, and ktor 0.9.5 to Kotlin 1.3.0, coroutines 1.0.0, and ktor 1.0.0-beta-3, I am getting
    e: org.jetbrains.kotlin.util.KotlinFrontEndException: Exception while analyzing expression at (20,26) in /path/to/ModuleCommand.kt
    Caused by: java.lang.AssertionError: Rewrite at slice FUNCTOR key: @kotlin.internal.InlineOnly public inline fun check(value: kotlin.Boolean, lazyMessage: () -> kotlin.Any): kotlin.Unit defined in kotlin[DeserializedSimpleFunctionDescriptor@2e20f454] old value: org.jetbrains.kotlin.contracts.model.functors.SubstitutingFunctor@7b9036fb@2073048827 new value: org.jetbrains.kotlin.contracts.model.functors.SubstitutingFunctor@5779296b@1467558251
    Caused by: java.lang.Throwable: Rewrite at slice FUNCTOR key: @kotlin.internal.InlineOnly public inline fun check(value: kotlin.Boolean, lazyMessage: () -> kotlin.Any): kotlin.Unit defined in kotlin[DeserializedSimpleFunctionDescriptor@2e20f454] old value: org.jetbrains.kotlin.contracts.model.functors.SubstitutingFunctor@7b9036fb@2073048827 new value: org.jetbrains.kotlin.contracts.model.functors.SubstitutingFunctor@5779296b@1467558251
    Where position (20, 26) is a
    kotlinx.coroutines.runBlocking
    call
    import kotlinx.coroutines.runBlocking
    
    11: object ModuleCommand : CliktCommand(...) {
           ...
    20:    override fun run() = runBlocking {
               ...
    50:    }
           ...
    63: }
    I still get this error after performing a Gradle clean. Has anyone experience this type of issue that figured out a fix?
    a
    • 2
    • 1
  • b

    bdawg.io

    10/29/2018, 6:27 PM
    Update: I had a
    check
    call inside of my functions. By commenting that line out, the code fully compiled. it appears to be an issue with inline function rewriting rather than coroutines itself The
    check
    call before (fails to compile):
    val path: String
    val group: String
    
    check(File("$path/src/main/kotlin/${group.replace(".", File.separator)}").mkdirs()) { "Failed to create directories for module" }
    d
    • 2
    • 3
  • j

    jcechace

    10/29/2018, 7:26 PM
    In roman’s talk at Kotlin conf it is recommended to define function which are a coroutine as an extension on
    CouroutineScope
    what if the coroutine is a method inside class? How is this going to behave?
    class Watcher {
        fun CoroutineScope.watcherStarted() = async {
    
        }
    }
    b
    • 2
    • 1
  • n

    Nikky

    10/29/2018, 7:31 PM
    you will be able to call it like this:
    with(watcher) { watcherStarted() }
    @jcechace
    z
    • 2
    • 6
  • t

    thevery

    10/29/2018, 7:54 PM
    With 1.0 release, is there any plans on native mt support in coroutines?
    l
    v
    g
    • 4
    • 6
  • i

    ivan.savytskyi

    10/29/2018, 11:58 PM
    fun main(vararg args: String) = runBlocking {
        try {
            val deferred = async {
                println("Throwing exception from async")
                throw ArithmeticException() // Nothing is printed, relying on user to call await
            }
            deferred.await()
            println("Unreached")
        } catch (e: ArithmeticException) {
            println("Caught ArithmeticException")
        }
    }
    h
    • 2
    • 1
  • n

    nemi

    10/30/2018, 12:11 AM
    About 1.3-M1 there was this statement
    > To ensure a smooth migration, we’ll add a compatibility layer in 1.3 and the classes for experimental coroutines will still remain in the standard library. The compiled Kotlin/JVM code that uses experimental coroutines from 1.1 or 1.2 would still continue to work in Kotlin 1.3.
    If I’m reading this libs complied experimental coroutines should still work. However that doesn’t seem to be the case. Is there a compiler flag that needs to be set or a separate artifact to be included that I’m not aware of
    🤔 1
    d
    v
    • 3
    • 9
Powered by Linen
Title
n

nemi

10/30/2018, 12:11 AM
About 1.3-M1 there was this statement
> To ensure a smooth migration, we’ll add a compatibility layer in 1.3 and the classes for experimental coroutines will still remain in the standard library. The compiled Kotlin/JVM code that uses experimental coroutines from 1.1 or 1.2 would still continue to work in Kotlin 1.3.
If I’m reading this libs complied experimental coroutines should still work. However that doesn’t seem to be the case. Is there a compiler flag that needs to be set or a separate artifact to be included that I’m not aware of
🤔 1
d

Dmytro Danylyk

10/30/2018, 11:23 AM
@Vsevolod Tolstopyatov [JB] @elizarov can you please help with the above question? Thanks in advance.
v

Vsevolod Tolstopyatov [JB]

10/30/2018, 9:21 PM
could you please specify what’s the problem? You can’t use older kotlinx.coroutines versions without eap prefix with Kotlin 1.3?
n

nemi

10/30/2018, 9:39 PM
@Vsevolod Tolstopyatov [JB] The situation is the following: there are 3rd party libraries we are using that use the experimental version of coroutines. We would like to bump to kotlin 1.3.0. When we bump and make changes on our end to use the non experimental version, the project compiles but crashes at runtime due to classes of the experimental implementation not being present. Maybe I have misunderstood what was written when 1.3-M1 came out, but I though that this case would be covered. Code will not compile with usage of experimental implementation using 1.3.0 but pre compiled code that uses experimental would still work (3rd party lib)
v

Vsevolod Tolstopyatov [JB]

10/31/2018, 8:22 AM
This is strange. Is it possible to extract small self-contained example from your problem?
Also, do you have two versions of
kotlinx.coroutines
and Kotlin in a classpath?
n

nemi

11/01/2018, 1:13 AM
@Vsevolod Tolstopyatov [JB] I have attached a small sample. It contains a dumbed down lib and an Android app project.
The library jar is copied over to app/libs/tacker.jar
sample.zip
Not quite clear on the classpath question 🤔 . If the artifact and group id are the same, gradle will pick the latest, thus only one version is present for both kotlin and coroutines
View count: 4