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

    Albert

    03/29/2019, 2:46 PM
    Is there a way with
    SupervisorJob
    to restart a coroutine when it stops exceptionally?
    supervisorScope {
      launch {
        throw Exception()
      }
    }
    r
    • 2
    • 1
  • r

    Robert Jaros

    03/29/2019, 5:52 PM
    What is the easiest way to convert ReceiveChannel<T> to Channel<T> ?
    o
    u
    d
    • 4
    • 12
  • j

    Jonathan Walsh

    03/29/2019, 11:31 PM
    I'm using
    CoroutineStart.UNDISPATCHED
    to help write
    CompletableFuture
    alternate methods to my suspending functions for use by Java. But I see its marked as
    @ExperimentalCoroutinesApi
    . Any recommendations / guidelines/ alternatives to using it? Or just be ready to uptake changes? Will post my specific example this thread
    • 1
    • 1
  • h

    Hexa

    03/30/2019, 12:10 AM
    i thought Kotlin 1.3 already includes coroutines package so i dont need to explicitly add dependency for coroutines?
    s
    t
    • 3
    • 2
  • r

    raulraja

    03/31/2019, 8:30 PM
    Hi, I'm micro-benchmarking some suspended methods in Arrow and I'm wondering given I have a very simple suspend function such as:
    suspend fun test(): Int = 0
    What is the fastest possible way to run the function via
    startCoroutine
    or similar in a blocking way to obtain
    0
    . This question is not specific to the coroutines-core lib but what I can do with the built in lang support for coroutines. I tried several conbinations with the EmptyCoroutineContext etc and using
    CountDownLatch
    and was wondering if that is the the only way to run a suspended function in a blocking way without using
    runBlocking
    e
    • 2
    • 3
  • o

    octylFractal

    04/01/2019, 12:18 AM
    use
    launch
    ➕ 1
    j
    • 2
    • 1
  • r

    rocketraman

    04/01/2019, 9:17 PM
    I have a suspend function, in which I want to start an
    async
    block. I'm assuming this is the right way?
    CoroutineScope(coroutineContext).async { ... }
    🇳🇴 1
    s
    b
    g
    • 4
    • 31
  • j

    jishindev

    04/02/2019, 6:55 AM
    Can anyone point me to a stable implementation of Event bus with Kotlin Coroutines which works along with the android lifecycles?
    t
    l
    • 3
    • 3
  • a

    addamsson

    04/02/2019, 12:38 PM
    I'm perusing the source code for the coroutines library and I bumped into this on `CoroutineContext`:
    Persistent context for the coroutine. It is an indexed set of [Element] instances.
    An indexed set is a mix between a set and a map.
    Every element in this set has a unique [Key]. Keys are compared _by reference_.
    is there a reason for not using a
    LinkedHashMap
    ? what are the performance characteristics of an indexed set?
    r
    s
    • 3
    • 2
  • a

    addamsson

    04/02/2019, 12:46 PM
    Another thing which I find a bit puzzling is that I have a class like this:
    class MyClass : CoroutineScope {
    
        override val coroutineContext = Dispatchers.Default + SupervisorJob()
    
        fun doSomething(): Job {
            val handler = CoroutineExceptionHandler { _, exception ->
                // ...
            }
            return launch(handler) {
                // ...
            }
        }
    }
    what I want to achieve is that child jobs (launched with
    launch
    ) can fail independently. This works right now but it also works if I remove
    + SupervisorJob()
    The docs say that if I add a
    CoroutineExceptionHandler
    to a coroutine it won't bubble exceptions up which is fine but in
    SupervisorJob
    I can see this:
    A failure or cancellation of a child does not cause the supervisor job to fail and does not affect its other children,
    so a supervisor can implement a custom policy for handling failures of its children:
    
    A failure of a child job that was created using [launch][CoroutineScope.launch] can be handled via [CoroutineExceptionHandler] in the context.
    so it implies that I can only use
    CoroutineExceptionHandler
    in a
    SupervisorJob
    yet it works without one. Did I miss something?
    a
    d
    • 3
    • 15
  • d

    Dico

    04/03/2019, 6:35 AM
    I tend to go against the pattern of implementing
    CoroutineScope
    in application components that use a coroutine lifecycle, favoring an approach using
    private val scope = CoroutineScope(...)
    That way the scope is not leaked by implementing the interface and it is in my opinion cleaner. It distinguishes better between using the scope and using the scope of a coroutine you created. What do you think? Why should we implement CoroutineScope the way it is suggested initially by structured concurrency?
    s
    a
    +2
    • 5
    • 9
  • j

    Jacques Smuts

    04/03/2019, 8:25 AM
    I just want to say thank you to whomever thought of this warning.
    g
    g
    s
    • 4
    • 29
  • s

    Slackbot

    04/03/2019, 1:34 PM
    This message was deleted.
    l
    c
    • 3
    • 2
  • t

    tseisel

    04/04/2019, 9:31 AM
    How to unit test that a
    suspend fun
    suspends until a certain condition is met ? I tried the following :
    runBlocking() {
        val testSource = BehaviorProcessor.create<String>()
        val subjectUnderTest = MyCache(coroutineScope = this, source = testSource)
    
        val loading = async(start = CoroutineStart.UNDISPATCHED) { subjectUnderTest.getCachedValue() } // Suspend function call
        assertFalse(loading.isCompleted)
        
        // Sending an element to that processor satisfies the condition
        testSource.onNext("Foo")
        assertTrue(loading.isCompleted) // This fails : isCompleted is false
    }
    g
    • 2
    • 2
  • c

    carlos cdmp

    04/04/2019, 12:41 PM
    Is there some reason why I should use the Retrofit Deferred adapter instead of just doing the synchronous .execute() and then come back to UI thread and handle the result?
    s
    • 2
    • 1
  • j

    jw

    04/04/2019, 12:43 PM
    The Retrofit adapter uses enqueue which means OkHttp can better multiplex over HTTP/2 and will honor per-host connection limits.
    c
    g
    • 3
    • 2
  • v

    Vsevolod Tolstopyatov [JB]

    04/04/2019, 1:25 PM
    📣 📣 📣
    kotlinx.coroutines
    1.2.0-alpha-2 is here! It has one major feature preview: cold streams aka
    Flow
    to work with asynchronous cold streams of data. The primary goal of the feature preview is to explore its possible strengths and weaknesses, evaluate real-world use-cases and finally adapt and refine it. Try it, use it, break it! Full API reference for `Flow`: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.flow/-flow/index.html
    🎉 34
    👍 1
    😒uspend: 22
    :kotlin: 24
    d
    g
    +3
    • 6
    • 15
  • s

    sdeleuze

    04/04/2019, 5:21 PM
    https://twitter.com/sdeleuze/status/1113853613884018688
    👍 10
    🎉 14
    l
    • 2
    • 2
  • k

    kevinskrei

    04/04/2019, 7:08 PM
    I'm attempting to use Realm in a suspend function. Realm only allows access to objects on the same thread. Is there a way to ensure that when a suspending call is made inside that function that it returns to the same thread as the caller? I've read about ThreadLocal but i've only seen examples when launching a coroutine and not within a suspend function. Or, is the only way to control the thread switching is from the parent calling
    <http://GlobalScope.xxx|GlobalScope.xxx>
    ? For example
    suspend fun sync() {
       Realm.getDefaultInstance().use { realm ->
              val variable = realm.getSomeVar()
              val result = service.execute() //<- suspending function
              val x = variable.y //<- Error because it returns to a different thread
       }
    }
    Thank you
    w
    • 2
    • 2
  • s

    sdeleuze

    04/05/2019, 6:37 AM
    Is Coroutines
    Flow
    usable in multiplatform projects?
    l
    d
    v
    • 4
    • 4
  • f

    Fredrik Larsen

    04/05/2019, 7:30 AM
    Can anyone shed some light on how you use coroutines in addition to RxJava? Specifically how you use suspending functions instead of Single/Maybe/Completable? I understand that for one-offs that works nicely, but what if you want to use that as part of your stream? Thanks
    g
    t
    s
    • 4
    • 14
  • s

    svenjacobs

    04/05/2019, 10:09 AM
    Hi guys, I need help with
    Job
    . When I add a
    Job
    instance to a
    CoroutineContext
    the behaviour of
    async
    changes in regards to exception handling. Suddenly exceptions within
    async
    are propagated to the default exception handler. On Android for example this causes the app to crash.
    try .. catch
    around
    await()
    don't help here. It seems that
    Job
    adds the default exception handler to the context. However I need
    Job
    so that I can cancel the context later. Here's an example (yes, it's Android but it's a generic problem, not related to Android)
    class TestActivity : Activity(),
                         CoroutineScope {
    
        override val coroutineContext: CoroutineContext = Dispatchers.Default + Job()
    
        override fun onCreate(savedInstanceState: Bundle?) {
            super.onCreate(savedInstanceState)
    
            val deferred = async {
                // App crashes here
                throw NullPointerException()
            }
    
            launch {
                try {
                    deferred.await()
                } catch (e: Exception) {
                    Log.e("TestActivity", "ERROR", e)
                }
            }
        }
    
        override fun onDestroy() {
            coroutineContext.cancel()
            super.onDestroy()
        }
    }
    How can I have the default behaviour of
    async
    where exceptions are only thrown on
    await()
    but also have the ability of a cancellable job in a context?
    l
    g
    • 3
    • 11
  • l

    louiscad

    04/05/2019, 10:59 AM
    Is
    withContext(<http://Dispatchers.IO|Dispatchers.IO>) { ... }
    equivalent to
    coroutineScope { ... }
    efficiency-wise if invoked from
    <http://Dispatchers.IO|Dispatchers.IO>
    ?
    v
    a
    +2
    • 5
    • 5
  • j

    Jacques Smuts

    04/05/2019, 1:36 PM
    continue_vs_return.kt
    r
    l
    • 3
    • 14
  • c

    cmgurba

    04/05/2019, 3:00 PM
    probably silly question, if i remove the
    job.cancel()
    from this snippet in the coroutine docs, why does playground time out entirely?
    fun main() = runBlocking {
    //sampleStart
        val job = launch {
            repeat(1000) { i ->
                println("I'm sleeping $i ...")
                delay(500L)
            }
        }
        delay(1300L) // delay a bit
        println("main: I'm tired of waiting!")
        job.cancel() // cancels the job
        job.join() // waits for job's completion 
        println("main: Now I can quit.")
    //sampleEnd    
    }
    l
    • 2
    • 9
  • p

    Paul Woitaschek

    04/06/2019, 8:19 AM
    This prints:
    [1a, 1b, 1c, 1d, 2d, 2e]
    . Why doesn't it start with
    1b
    ?
    -.kt
    o
    • 2
    • 3
  • j

    Jakub Aniola

    04/07/2019, 12:07 PM
    I want to painlessly convert some java threads code to kotlin coroutines. There is some code which creates as much threads as much as
    Runtime.getRuntime().availableProcessors()
    allows. Is there any common rule how much I should handle this situation in kotlin coroutines? Totally coroutines n00b here
    -.java
    g
    • 2
    • 3
  • t

    tseisel

    04/07/2019, 1:52 PM
    Now that
    Flow
    is there, are channels still the right tool for wrapping callback APIs with `registerListener`/`unregisterListener` ? Looks like
    flowViaChannel
    has been written for that purpose, but I don't see a way to "close" a
    Flow
    like with channels and Flowables
    ➕ 1
    g
    • 2
    • 1
  • p

    Philippe Boisney

    04/07/2019, 3:14 PM
    Hey there! I'm looking for feedback. I'm trying to implement
    NetworkBoundResource
    with Coroutines (instead of
    Executor
    like the Google sample https://github.com/googlesamples/android-architecture-components/blob/master/GithubBrowserSample/app/src/main/java/com/android/example/github/repository/NetworkBoundResource.kt). I also want that
    NetworkBoundResource
    return a
    LiveData
    through the method
    asLiveData()
    . 1️⃣ My first try was to pass a
    CoroutineScope
    to the constructor of
    NetworkBoundResource
    , to properly manage cancellation. Pros: in this way, tasks are canceled when a ViewModel is cleared for example. Cons: My
    UserRepository
    methods ask for parameter a
    CoroutineScope
    for each call 🔗 https://gist.github.com/PhilippeBoisney/47b9eaee02df537cf7b0703707243a78 2️⃣ My second try was to use a
    GlobalScope
    to launch the Coroutines inside the
    NetworkBoundResource
    . Pros: No more
    CoroutineScope
    passed through `UserRepository`methods parameters. Cons:
    GlobalScope
    should be avoided (even if in Google sample, they use
    Executor
    the same way of a
    GlobalScope
    ) 🔗 https://gist.github.com/PhilippeBoisney/4a5fc718a2b8d9735bdf2a5bfb37aebe Which one of those approaches do you prefer? If none, how will you do? :thread-please:
    2️⃣ 1
    :thread-please: 1
    1️⃣ 6
    s
    d
    j
    • 4
    • 6
  • s

    Sam

    04/08/2019, 12:33 AM
    Why is the handler ignored in this case?
    fun main() {
    
        val handler = CoroutineExceptionHandler { _, throwable ->
            println("Exception $throwable")
        }
    
        runBlocking {
    
            val scope = CoroutineScope( coroutineContext + handler )
    
            scope.launch {
                throw Exception()
            }.join()
        }
    
        println( "main done" )
    }
    o
    g
    • 3
    • 25
Powered by Linen
Title
s

Sam

04/08/2019, 12:33 AM
Why is the handler ignored in this case?
fun main() {

    val handler = CoroutineExceptionHandler { _, throwable ->
        println("Exception $throwable")
    }

    runBlocking {

        val scope = CoroutineScope( coroutineContext + handler )

        scope.launch {
            throw Exception()
        }.join()
    }

    println( "main done" )
}
o

octylFractal

04/08/2019, 4:07 AM
I believe unless you use
supervisorJob
, child jobs propagate exceptions outwards: https://kotlinlang.org/docs/reference/coroutines/exception-handling.html#exceptions-in-supervised-coroutines
indeed, from earlier on that page:
If a coroutine encounters exception other than CancellationException, it cancels its parent with that exception. This behaviour cannot be overridden and is used to provide stable coroutines hierarchies for structured concurrency which do not depend on CoroutineExceptionHandler implementation. The original exception is handled by the parent when all its children terminate.
g

gildor

04/08/2019, 12:17 PM
+1 to Kenzie, just want to add that from this example hard to recommend correct solution without some real example
s

Sam

04/08/2019, 1:05 PM
This was just to get an idea of the exception handler
@octylFractal Setting up the scope without context does invoke the handler which is what led me to try add a context and see what happens
val scope = CoroutineScope( handler )
g

gildor

04/08/2019, 1:25 PM
this approach just incorrect in general with Job
s

Sam

04/08/2019, 1:26 PM
you mean without a job?
g

gildor

04/08/2019, 1:26 PM
you cannot prevent scope with Job to throw exception on child error
you have to use SupervisorJob instead
s

Sam

04/08/2019, 1:28 PM
Tried this and handler is invoked and scope doesn't rethrow. so what am i missing?
val scope = CoroutineScope( Job() + handler )
g

gildor

04/08/2019, 1:28 PM
again, hard to recommend something without real use case
again, it’s incorrect
this is how Job works
s

Sam

04/08/2019, 1:29 PM
Not about a use case, just figuring out how exceptions work
g

gildor

04/08/2019, 1:29 PM
I mean it’s not incorrect by itself
it’s just doesn’t work how you expect with Job
did you read official doc? https://github.com/Kotlin/kotlinx.coroutines/blob/master/docs/exception-handling.md
I just want tell you, that there are many unnecessary components in your code and not how it should be used in any real code
For example I can rewrite it like this:
fun main() {
    try {
        runBlocking {
            launch {
                throw Exception()
            }
        }
    } catch(throwable: Exception) {
        println("Exception $throwable")
    }

    println( "main done" )
}
This will be the same code as above that uses coroutines and exception handling properly, how you expect it
s

Sam

04/08/2019, 1:36 PM
Got it, I was just curious at what factors influenced the behavior one way or the other in my case
g

gildor

04/08/2019, 1:39 PM
Yes, this covered in doc that Kenzie sent in his first comment
also, in your case you use runBlocking which throws exception that impossible prevent without wrapping code inside to try/catch (for regular or suspend code), or without supervisorJob, which is covered in section “Exceptions in supervised coroutines” of this doc
s

Sam

04/08/2019, 2:30 PM
Yeah, so looks like using coroutineContext from runBlocking's scope creates a parent-child coroutine and that explains the bail out. Without coroutineContext, the coroutine launched with a new scope behaves like a GlobalScope and uses the handler
g

gildor

04/08/2019, 4:42 PM
Yes, correct, also in general usage of CoroutineScope() builder often a sign that something went wrong
View count: 4