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
  • b

    bloder

    11/12/2018, 12:33 PM
    I don't know if this error is directly related to coroutines but started when I implement it... One problem here, I have an android app and I've implemented coroutines in one part of it, the problem is that is showing this error when I try to build:
    error: cannot access HttpResult
        kotlin.coroutines.Continuation<? super HttpResult<MyEntity>> p2);
    
    bad class file: HttpResult.class
    undeclared type variable: R
        Please remove or make sure it appears in the correct subdirectory of the classpath.
    I don't know why but byte code could not find my HttResult class (it's a inline class), I don't know if it's a dependency problem, because I'm importing kotlin(v 1.3.0) and coroutines(v 1.0.0) dependencies in two different modules, but I've already tried to change the versions and dependencies but I could not fix it. Do you guys already got a problem like this before?
    • 1
    • 1
  • s

    suppoze

    11/12/2018, 1:58 PM
    Hi all, Is there a Kotlin coroutine implementation equivalent to
    private val queue = Executors.newSingleThreadExecutor()
    //...
        fun submit(data: Data) {
            queue.submit { updateData(data) }
        }
    ? I was thinking about
    private val queue = Executors.newSingleThreadExecutor().asCoroutineDispatcher()
    // ...
        fun submit(data: Data) = runBlocking {
            launch(queue) {
                updateData(data)
            }
        }
    but it's seems to be running sequentially somehow? Am I doing something wrong?
    m
    g
    • 3
    • 9
  • h

    hho

    11/12/2018, 2:00 PM
    How should a single thread executor not be sequential?
    s
    • 2
    • 1
  • j

    Javier

    11/12/2018, 2:29 PM
    but with Globalscope.launch no
    g
    • 2
    • 1
  • j

    Javier

    11/12/2018, 2:29 PM

    https://i.imgur.com/RlhpZyq.png▾

    g
    • 2
    • 2
  • z

    zak.taccardi

    11/12/2018, 4:46 PM
    if you use
    .launch
    or
    .async
    , use the
    Dispatchers.Unconfined
    which should help the coroutine finish before your test does
    👌 1
    g
    • 2
    • 11
  • r

    rocketraman

    11/12/2018, 10:33 PM
    If I pass in the coroutine scope from the caller, it works fine, but it feels silly to add a parameter for that.
    l
    g
    • 3
    • 45
  • s

    spierce7

    11/13/2018, 3:10 AM
    I'm seeing a strange exception in Android with ktor and coroutines. Anyone ever seen this before?
    java.lang.IncompatibleClassChangeError: Class kotlinx.coroutines.io.internal.MutableDelegateContinuation implements non-interface class kotlinx.coroutines.DispatchedTask (declaration of 'kotlinx.coroutines.io.internal.MutableDelegateContinuation'
    o
    • 2
    • 2
  • a

    Alexander

    11/13/2018, 10:35 AM
    I want to use
    ktor
    http client with
    nodejs
    and found out that
    Js
    engine only works within browser environment. So I took code of js engine and try to adopt it to work with
    http
    module of nodejs. But it uses streams to read data (an example of how to read data: https://nodejs.org/api/http.html#http_http_request_url_options_callback). And I can't figure out how to do it better. Now I pass all data via channel:
    class ResponseReader(response: IncommingMessage) {
        private val chunksChannel = Channel<ByteArray>(UNLIMITED)
    
        init {
            response.on("data") { chunk: Uint8Array ->
                chunksChannel.offer(chunk.asByteArray())
            }
            response.on("end") { ->
                chunksChannel.close()
            }
        }
    
        suspend fun readChunk(): ByteArray? {
            return try {
                chunksChannel.receive()
            } catch (exc: ClosedReceiveChannelException) {
                null
            }
        }
    }
    With this solution I cannot cancel reading data. Also as I understand it misses a backpressure propagation thus if data arrives faster then we can process it may lead to a huge memory consumption.
    g
    • 2
    • 10
  • f

    functionaldude

    11/13/2018, 1:46 PM
    I’m trying to understand how scopes are ment to use. I have a sample implementation of a
    mapAsync
    function. The goal here is to process and map the result of every item asynchronously, but I want to cancel all tasks as soon as one of them fail, also I don’t want to cancel the parent scope. What do you think of this example:
    🤔 1
    d
    m
    • 3
    • 2
  • f

    functionaldude

    11/13/2018, 1:46 PM
    t
    • 2
    • 1
  • m

    mersan

    11/13/2018, 4:19 PM
    is there a way to prevent the scope/job from running twice on the same time?
    a
    • 2
    • 1
  • m

    mersan

    11/13/2018, 4:20 PM
    looking into the implementation of Job() method, it will create
    active
    job by default
    a
    • 2
    • 3
  • t

    timrijckaert

    11/13/2018, 4:49 PM
    How can I test a suspending function in multiplatform? Suppose I have following function:
    suspend fun CoroutineScope.foo() : ReceiveChannel<List<Int>> =
        produce {
            launch {
                val cache = cache.getCachedInts()
                offer(cache)
            }
            launch {
                val network = network.getNetworkInts
        
                if (network.isNotEmty()) {
                    cache.cacheInts(network)
                }
        
                offer(network)
            }
        }
    I tried
    runBlocking
    but it seems unavaible in MPP?
    g
    m
    • 3
    • 5
  • m

    mersan

    11/13/2018, 9:11 PM
    this error has nothing to do with coroutines, make sure your app has the internet premission, and the device reaches to the server you are trying to acess
    • 1
    • 1
  • t

    Tolriq

    11/13/2018, 9:33 PM
    I’m not using retrofit 😉 And yes I do receive 99,99% of them 😉 Sometimes catch does not work. I should really learn to write better English.
    g
    • 2
    • 2
  • t

    tateisu

    11/13/2018, 9:44 PM
    Perhaps, rather than directly using suspendCancellableCoroutine {}, I think that it is safer to await () after creating Deferred https://github.com/JakeWharton/retrofit2-kotlin-coroutines-adapter/blob/master/src/main/java/com/jakewharton/retrofit2/adapter/kotlin/coroutines/CoroutineCallAdapterFactory.kt#L87
    👍 1
    g
    • 2
    • 1
  • g

    gildor

    11/14/2018, 7:43 AM
    @elizarov And what is recommended way to handle it?
    tryResumeWithException
    ? I understand this behaviour, avoid exception swallowing, but in this particular case looks that this is the only valid option
    e
    t
    • 3
    • 17
  • r

    rook

    11/14/2018, 2:48 PM
    Is there a way to reactivate a cancelled job, or do I need to instantiate a new one?
    e
    • 2
    • 2
  • s

    spierce7

    11/14/2018, 5:19 PM
    Can anyone explain to me why coroutine exception handling is treated differently between Job and Deferred? Doesn't initially make sense to me why this is desired: https://github.com/Kotlin/kotlinx.coroutines/blob/master/docs/exception-handling.md
    v
    • 2
    • 2
  • i

    ivan.savytskyi

    11/14/2018, 8:17 PM
    Question regarding
    kotlinx.coroutines.AwaitKt#awaitAll
    . From KDocs:
    Awaits for completion of given deferred values without blocking a thread and resumes normally with the list of values when all deferred computations are complete or resumes with the first thrown exception if any of computations complete exceptionally including cancellation.
    If I understand that right
    resumes with the first thrown exception
    . But having this example:
    val exceptionHandler = CoroutineExceptionHandler { _, exception ->
            println("exception handler $exception")
        }
        val scope = CoroutineScope(Dispatchers.Default + exceptionHandler)
        scope.launch {
            val firstCoroutine = async {
                delay(300)
                println("crashing first coroutine")
                throw IllegalArgumentException()
            }
    
            val secondCoroutine = async {
                try {
                    delay(700)
                    println("second coroutine still alive")
                } catch (e: Exception) {
                    println("second coroutine try/catch $e")
                }
                "Done"
            }
    
            try {
                awaitAll(firstCoroutine, secondCoroutine)
            } catch (e: Exception) {
                println("awaitAll try/catch $e")
            }
        }
    I was expecting to see
    awaitAll try/catch  java.lang.IllegalArgumentException
    but instead I see
    awaitAll try/catch kotlinx.coroutines.JobCancellationException: Job is cancelling; job=StandaloneCoroutine{Cancelling}@27e6316a
    . Could someone pls explain this behaviour?
    b
    t
    • 3
    • 21
  • m

    maxime

    11/15/2018, 1:24 PM
    Hi! I’m in the process of migrating my coroutines from Kotlin 1.2.x (\o/) I see that the concept of Reference (with
    asReference()
    ) is gone, what is the way to go now? Should I use
    WeakReference
    instead, rely on the coroutine state, or trust the current CoroutineScope?
    e
    g
    • 3
    • 4
  • i

    irus

    11/15/2018, 3:01 PM
    withTimeoutOrNull(1000) {
        suspendCancellableCoroutine<Unit> { cont ->
            cont.invokeOnCancellation {
                cont.resumeWithException(CancellationException("Hello!")) // 1
                cont.resumeWithException(RuntimeException("Hello!")) // 2
            }
        }
    }
    Can't find place in documenation where difference between (1) and (2) described
    a
    e
    • 3
    • 8
  • s

    spierce7

    11/15/2018, 10:06 PM
    Is there any way to re-run a coroutine automatically without putting it in a while loop, or will I have to wait for cold streams for something like that? I'm trying to build in some automatic error handling, and if a coroutine errors out due to something like a network exception, a common behavior would be that the user can select that the request would be re-run.
    g
    e
    +2
    • 5
    • 8
  • k

    kenkyee

    11/16/2018, 1:08 AM
    For catching exceptions with coroutines with the usual: catch (exception: Exception) What do people go about lint flagging this as too generic an exception? Just suppress the warning all the time? 🙂
    g
    e
    • 3
    • 11
  • z

    zak.taccardi

    11/16/2018, 1:09 AM
    coroutines generally shouldn’t throw exceptions
    g
    • 2
    • 1
  • g

    groostav

    11/16/2018, 7:12 AM
    Hey guys, I've got a question about parent-child coroutines: what do I do if I want to start a coroutine that might not complete: should I set its parent to the caller or not?
    //producer function following conventional (?) coroutine parent-child-ing as per Romans Coroutines part II at kotlinconf 2018
    fun CoroutineScope.longRunningProducer(): RecieveChannel<Info> { ... }
    
    //then a user
    fun someUser(){
      println("started!")
      runBlocking {
    
        val selfScope: CoroutineScope = this@runBlocking
        val producer: RecieveChannel<Info> = selfScope.longRunningProducer()
    
        for(item in producer){
          if(businessLogic(item)) {
            //bail!
            break;
          }
          else //...
        } 
        println("almost done!")
      }
      println("done!")
    }
    if
    longRunningProducer
    never returns never stops producing values on its returned channel --which is reasonable-- and dispatches a child coroutine that runs forever, then your output will be
    started!
    almost done!
    because the
    nestedEventLoop
    wont close until its children are done. What I'd like to have happen is for an abandoned
    longRunningProducer
    coroutine to simply get garbage collected, but I guess that means I gotta be careful with
    weakReferences
    and such, yeah?
    g
    • 2
    • 11
  • g

    gildor

    11/16/2018, 2:11 PM
    Dispatchers share threads, you run both of those coroutines inside a coroutine that uses Default dispatcher Each of dispatchers has own thread policy, but try to reuse existing thread to avoid context switch More details: https://github.com/Kotlin/kotlinx.coroutines/issues/261
    m
    • 2
    • 3
  • p

    Paul Woitaschek

    11/16/2018, 3:37 PM
    Now in rare conditions line 6 is being executed after I cancelled the job.
    v
    t
    • 3
    • 18
  • u

    uli

    11/17/2018, 1:56 PM
    Channels
    g
    g
    • 3
    • 7
Powered by Linen
Title
u

uli

11/17/2018, 1:56 PM
Channels
g

ghedeon

11/18/2018, 1:04 AM
do you use "raw" channels? I've seen that coroutines library on the top of Reactive Streams.
g

gildor

11/18/2018, 5:29 AM
Coroutines library on the top of Reactive streams? What do you mean?
For now channels (not sure what you mean about "raw") is the only stream-like abstraction in kotlinx.coroutines. later cold streams will be available (which is closet to Rx)
g

ghedeon

11/21/2018, 4:35 PM
it's from java 9: https://github.com/Kotlin/kotlinx.coroutines/tree/master/reactive/kotlinx-coroutines-reactive
but I've got the idea, thank you
g

gildor

11/22/2018, 2:35 AM
This is just an adapter Coroutines -> Rx and Rx -> Coroutines If you use any reactive-stream implementation and want to use Coroutines, this adapter is must have for you
u

uli

11/22/2018, 7:39 AM
I meant https://github.com/Kotlin/kotlinx.coroutines/blob/master/docs/channels.md#channels-experimental
View count: 3