https://kotlinlang.org logo
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
  • z

    Zach Klippenstein (he/him) [MOD]

    09/15/2018, 5:28 PM
    It seems like `CoroutineExceptionHandler`s are ignored for exceptions thrown from a coroutine `launch`ed with a parent
    Job
    from a
    runBlocking
    scope. Changing the dispatcher doesn’t seem to matter, and coroutines `launch`ed from
    GlobalScope
    execute the handler as I’d expect. I can’t see any documentation about this or figure out how this makes sense. E.g.
    fun main(args: Array<String>) {
      val handler = CoroutineExceptionHandler { _, exception ->
        println("Caught $exception")
      }
    
      runBlocking(handler) {
        val job = launch {
          // This exception is thrown from runBlocking, and not seen by handler.
          throw AssertionError()
        }
        job.join()
      }
    }
    If you change that to the following,
    handler
    gets run:
    runBlocking {
      val job = GlobalScope.launch(handler) {
    Is this behavior by design?
    d
    e
    s
    • 4
    • 10
  • k

    Kotlin

    09/15/2018, 8:02 PM
    Hello everyone I am stuck on a kotlin coroutine. Appreciate if someone can help me on that. I am launching a coroutine that after a specified delay display a counter value on the screen. job = launch(UI) { var count= 0 while (true) { textView.text = "${count++}" delay(200L) } } } Now on screen rotation I want UI keeps getting updated with correct counter value. Does someone has any idea how to resume the job on configuration(e.g. screen rotation) change?
    t
    p
    +3
    • 6
    • 7
  • a

    acando86

    09/16/2018, 9:29 AM
    I might have missed this before or in the documentation, but are there best practises to handle the new CorotuineScope in fragments (in particular where to attach and cancel an instance of a Job)? Are onAttach/onDetach of the parent activity a good choice? Probably it's more a question for the Android channel, but i've posted here because it is coroutine-related
    l
    g
    • 3
    • 6
  • z

    zjuhasz

    09/16/2018, 11:55 AM
    I'm trying to update some library code to coroutines 0.26 and I am noticing some boilerplate patterns. If I'm not mistaken, we want every class that launches its own coroutines to be a
    CoroutineScope
    , unless the coroutines created by that class should always act globally for the full lifetime of the application. This means every class that launches coroutines should be created through an extension function on
    CoroutineScope
    like
    CoroutineScope.MyClass()
    . So
    MyClass
    needs a constructor that takes scope as a parameter, then we need to make an extension function for
    CoroutineScope
    that is an exact copy of the constructor for
    MyClass
    except it uses
    this
    from
    CoroutineScope
    instead of taking scope as a parameter. If there is a class with several constructors that each have several parameters this can be really annoying and a bit hard to maintain. Is there a better way for me to be scoping the coroutines launched by classes?
    p
    d
    e
    • 4
    • 12
  • a

    ashdavies

    09/17/2018, 7:53 AM
    Is there an idiomatic way to override the default dispatcher for unit tests? or would this be considered bad practice, and typical injection preferred?
    g
    s
    • 3
    • 9
  • p

    Pavel.AZ

    09/17/2018, 12:45 PM
    Well, I'm really glad that I joined KotlinConf workshop in Amsterdam with @elizarov , Hope version 0.26.0 "structured concurrency" will be presented😄
    e
    • 2
    • 1
  • m

    Martin Devillers

    09/17/2018, 1:01 PM
    I’m curious about the example in the coroutines guide for structured concurrency on Android :
    abstract class ScopedAppActivity: AppCompatActivity(), CoroutineScope {
        protected lateinit var job: Job
        override val coroutineContext: CoroutineContext 
            get() = job + Dispatchers.Main
        
        override fun onCreate(savedInstanceState: Bundle?) {
            super.onCreate(savedInstanceState)
            job = Job()
        }
            
        override fun onDestroy() {
            super.onDestroy()
            job.cancel()
        } 
    }
    https://github.com/Kotlin/kotlinx.coroutines/blob/master/ui/coroutines-guide-ui.md#structured-concurrency-lifecycle-and-coroutine-parent-child-hierarchy It seems to me that this example is needlessly complicated. The following would work just as well.
    abstract class ScopedAppActivity: AppCompatActivity(), CoroutineScope {
        override val coroutineContext: CoroutineContext = Job()
    
        override fun onDestroy() {
            super.onDestroy()
            coroutineContext[Job]?.cancel()
        }
    }
    Since
    Dispatchers.Main
    is the
    ContinuationInterceptor
    used when none is available in a
    CoroutineContext
    , this should yield the same result. Is there something I’m missing?
    p
    • 2
    • 2
  • a

    ashdavies

    09/17/2018, 1:22 PM
    @cb has a nice Gist on using
    CoroutineScope
    with
    LifecycleObserver
    so you can avoid having to use inheritance
    m
    • 2
    • 1
  • a

    Albert

    09/17/2018, 1:44 PM
    I have a strange issue, but I am not sure if it is related to coroutines. But I have the following unit test:
    @Test fun testActor() {
      val testActor = actor<String> {
        println(channel.receive())
      }
    
      testActor.sendBlocking("CHANNEL-MESSAGE")
    }
    When I run this locally on my machine I see
    CHANNEL-MESSAGE
    being printed. But when I build this with docker it is never received. My
    Dockerfile
    looks like:
    FROM maven:3.3.9-jdk-8
    COPY . project/
    WORKDIR project
    RUN mvn clean package
    I used version
    3.3.9
    which is the same on my local machine. With docker it actually freezes on the
    sendBlocking
    . Anyone a clue how this is possible?
    g
    • 2
    • 11
  • j

    Jonathan

    09/17/2018, 2:34 PM
    Here if
    unsafeMethod
    fails it will make the parent job fail, which basically mean a crash of the UI componenent (any working coroutine will be cancelled and further action would no longer work) Of course I could encapsulate the call in
    try-catch
    . But it is a bit boilerplate and easy to forget. (here it is obvious, but what about unexpected exceptions?) How could I launch a child coroutine in a way that it does'nt propagate the failure to the parent?
    -.kt
    p
    k
    e
    • 4
    • 16
  • n

    nwh

    09/17/2018, 9:02 PM
    I'm getting a
    call to 'resume' before 'invoke' with coroutine
    error, but I'm having a hard time figuring out what's causing it and I can't seem to isolate it (though I can reproduce in this single environment). Any suggestions on how to track it down?
    v
    e
    • 3
    • 9
  • a

    Allan Wang

    09/17/2018, 10:00 PM
    Are there examples on how to handle exceptions during
    launch
    blocks? I have a method created like so:
    suspend fun <T> Deferred<T>.awaitOrRedirect(context: Context): T? =
        try {
            await()
        } catch (e: Exception) {
            logd("Error, redirect to Login")
            LoginActivity.launch(context)
            null
        }
    But the errors seem to just pass through and cancel the coroutines altogether without launching the activity. To give more details, I’m building for Android, and I’m using
    CoroutineScrope
    within the activity that is calling the method. I’m using
    launch
    as it is used for most of the example code, and it looks like the only difference with
    async
    is that
    async
    cancels the parent and returns a deferred value. I also see that there are `CoroutineExceptionHandler`s, though I’m not sure if that is the right fit here.
    g
    • 2
    • 11
  • t

    takahirom

    09/18/2018, 2:04 AM
    Hello, I would like to replace RxJava with Kotlin coroutine. I wrote it in RxJava as follows.
    kotlin
        api.fetchPersons()
            .subscribeOn(scheduler)
            .subscribe(
                { persons ->
                  showPersons(persons)
                },
                { e ->
                  showErrorDialog(e)
                })
    I enclosed with try catch to do the same on kotlin coroutines as follows. But in this case CancellationException did not go to parents job, so I thought that it would be in an invalid state. Even if CancellationException is caught by the user, the outer block is not just canceled, is there no problem? Is it fine just like this?
    kotlin
        launch { 
          try {
            val persons = api.fetchPersons() // suspend function
            showPersons(persons)
          } catch (e: Throwable) {
            showErrorDialog(e)
          }
        }
    g
    • 2
    • 8
  • l

    louiscad

    09/18/2018, 10:07 AM
    Hey, how do you manage to dispatch the progress of a long running
    suspend fun
    ? I'd like to see the approaches you prefer
    j
    • 2
    • 1
  • g

    gildor

    09/18/2018, 10:11 AM
    I usually just pass lambda for progress. Much less overhead than channel. But you can get callback on a different thread, so should handle this case
    ➕ 1
    l
    d
    +2
    • 5
    • 21
  • n

    Nikky

    09/18/2018, 10:58 AM
    so apparently user of my program encounters deadlock issues rnadomly in my program, apparently in a area of the code where i use coroutines and channels but the worst is.. i cannot manage to reproduce it with the same input data on my hardware would i be able to use visualvm to see where it is blocking itself? i also did not quite rule out that ktor-client-cio is not at fault, but again no idea how to test that :thread-please:
    v
    • 2
    • 3
  • v

    voddan

    09/18/2018, 1:58 PM
    Why do I have to use
    coroutineScope {  }
    only inside another coroutine or a suspending function? What's wrong with
    fun main() = coroutineScope { <do the majic> }
    ? Do I need
    runBlocking{}
    there? What's the meaning of
    runBlocking
    with scoped coroutines if scopes wait for their children?
    v
    d
    • 3
    • 18
  • d

    Dico

    09/19/2018, 2:42 AM
    coroutineContext
    is a top level property that can be accessed from suspend functions. I suspect that it does this under the hood:
    get() = suspendCoroutineUninterceptedOrReturn { cont -> cont.context }
    g
    • 2
    • 2
  • a

    aaverin

    09/19/2018, 5:14 AM
    Can a
    suspend
    function somehow find out in which dispatcher/executor is it running now?
    g
    • 2
    • 8
  • j

    jovmit

    09/19/2018, 11:38 AM
    I have a class that does file download. I have a function that triggers a download, and returns LiveData with the download progress. For each new call it would return new LiveData and it works nicely when I download 1 file. Now I want to launch new coroutine for each file download under the same scope, so I can cancel all at once if I want to. Can someone help with different ways to do this? or maybe what would be the best way? So I need to launch separate coroutine for each new call to the function, and add it under the same context.
    g
    d
    • 3
    • 3
  • v

    Vsevolod Tolstopyatov [JB]

    09/19/2018, 3:24 PM
    📣 📣 📣
    kotlinx.coroutines
    version
    0.26.1
    . Asynchronous Main dispatcher on Android, various bug fixes and improvements. See https://github.com/Kotlin/kotlinx.coroutines/releases/tag/0.26.1
    🎉 7
    e
    • 2
    • 3
  • h

    Harun

    09/19/2018, 9:11 PM
    Any resources for implementing coroutines+ retrofit 2 especially when one wants to chain multiple calls
    g
    • 2
    • 6
  • d

    danny

    09/19/2018, 10:17 PM
    On
    0.26.0
    I see in the release notes that
    Dispatchers.Default
    is now default dispatcher, but I had some existing code that was roughly
    runBlocking { someList.map { async { <do stuff with 'it'> } }.map { it.await } }
    that previously ran on
    CommonPool
    by default, but after the upgrade is constrained to the main thread. Guess I'm missing some detail around the structured concurrency changes...
    b
    • 2
    • 5
  • e

    elizarov

    09/20/2018, 6:40 AM
    @bj0 you don’t need an extra
    coroutineScope
    . The
    launch
    already provides one.
    b
    • 2
    • 3
  • b

    bj0

    09/20/2018, 4:33 PM
    when you create a
    CoroutineScope
    object, is there a way to wait for it to finish (like
    coroutineScope
    waits)?
    e
    • 2
    • 4
  • t

    travis

    09/20/2018, 6:33 PM
    In the structured concurrency example for Android (https://github.com/Kotlin/kotlinx.coroutines/blob/master/ui/coroutines-guide-ui.md#structured-concurrency-lifecycle-and-coroutine-parent-child-hierarchy),
    Dispatchers.Main
    is added to the
    job
    to make it so the dispatcher used for child coroutine builders will be
    Dispatchers.Main
    (correct me if I'm wrong). Which dispatcher is used if the
    + Dispatchers.Main
    portion is omitted?
    override val coroutineContext: CoroutineContext 
        get() = job
    e
    • 2
    • 2
  • s

    sdeleuze

    09/21/2018, 8:25 AM
    0.26.1
    seems available but not
    0.26.1-eap13
    , is that expected ?
    j
    v
    e
    • 4
    • 19
  • v

    vaskir

    09/21/2018, 9:20 AM
    Where is
    future
    function gone? There is no
    GlobalScope.future
    .
    j
    • 2
    • 1
  • v

    vaskir

    09/21/2018, 9:30 AM
    maybe I should reference a special library to make it work?
    j
    • 2
    • 8
  • e

    elizarov

    09/21/2018, 9:52 AM
    Hi, there! Do you think it is worth supporting
    rx1
    :yes: integration module on
    kotlinx.coroutines
    release or can we just drop it 🇳🇴 and provide only
    rx2
    integration? Please vote or tell your opinion in a thread.
    :yes: 1
    🇳🇴 34
    a
    • 2
    • 1
Powered by Linen
Title
e

elizarov

09/21/2018, 9:52 AM
Hi, there! Do you think it is worth supporting
rx1
:yes: integration module on
kotlinx.coroutines
release or can we just drop it 🇳🇴 and provide only
rx2
integration? Please vote or tell your opinion in a thread.
:yes: 1
🇳🇴 34
a

alex2069

09/21/2018, 10:28 AM
If someone really wants rx1 support they can use the RxJava compat lib - and as mentioned by @gildor below - it's not even officially supported anymore
View count: 4