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

    benny.huo

    04/21/2019, 1:55 AM
    Hey guys, I think there is a problem when calling
    join
    on an exceptionally completed job. After days digging, I figure out that if the
    join
    call falls into the fast-path or successfully suspending, a CancellationException will be thrown in this case, but if the
    join
    call falls into the
    joinSuspend
    path but not successfully suspending, no CancellationException will happen. I just wonder that is it a bug to get inconsistent result from
    join
    with the same code? I have created a gist here https://gist.github.com/enbandari/0321cffa792e0f98d90e0e77682aeaed to make it more clear.
    b
    e
    • 3
    • 6
  • t

    Thomas

    04/21/2019, 4:55 PM
    Is there an example somewhere how to implement switchMap for Kotlin Flows?
    l
    s
    s
    • 4
    • 11
  • a

    Allan Wang

    04/22/2019, 6:13 AM
    Is
    runBlocking
    safe for production if we have helper suspended functions, and are using an interface where it’s okay to block the thread? For instance, I’m building a notification widget, which requires updates to be done in
    onDataSetChanged
    , before the provider will apply the data
    g
    s
    • 3
    • 14
  • t

    Thomas

    04/22/2019, 7:21 PM
    Why does the following code crash with a null exception?
    val channel = ConflatedBroadcastChannel(Unit)
    channel.asFlow().produceIn(GlobalScope).poll()!!
    If I understand correctly this shouldn’t be happening because the channel has a default
    Unit
    value. The following code, however, does not crash:
    val channel = ConflatedBroadcastChannel(Unit)
    channel.openSubscription().poll()!!
    I don’t get why this works but the first example doesn’t. Could someone please explain this behaviour?
    g
    • 2
    • 12
  • s

    sdeleuze

    04/23/2019, 6:58 AM
    I need to adapt a suspending function that returns
    Flow
    to a non-suspending function that returns
    Flow
    . Is this the correct way to do that?
    suspend fun suspendingFlow(): Flow<String> { ... }
    
    fun nonSuspendingFlow() = flow {
    	suspendingFlow().collect {
    		emit(it)
    	}
    }
    v
    • 2
    • 5
  • a

    addamsson

    04/23/2019, 6:59 AM
    I'm trying to write a fire-and-forget service which offloads jobs to worker threads am I doing it the right way? I don't want the
    Test
    service to fail even if the
    Job
    fails because each
    Job
    is independent, I just want the error handling.
    class Test : CoroutineScope {
    
        override val coroutineContext = Dispatchers.Default + SupervisorJob()
    
        fun doSomething(): Job {
            val handler = CoroutineExceptionHandler { _, exception ->
                // log error
            }
            return launch(handler) {
                // do things
            }
        }
    }
    g
    • 2
    • 9
  • r

    ribesg

    04/23/2019, 8:59 AM
    I’m still not sure about coroutine extensions, does this look ok to you?
    suspend fun <T> withMinimumDuration(duration: Long, block: suspend CoroutineScope.() -> T) =
        coroutineScope {
            val delay = async { delay(duration) }
            val task = async { block() }
            delay.join()
            task.await()
        }
    g
    • 2
    • 41
  • j

    Jakub Aniola

    04/23/2019, 10:36 AM
    After converting some threads code to coroutines code, my benchmarks showed that memory consumption decreases but execution time is much longer with coroutines. I watched some talks and read multiple articles says that coroutines are “very light-weight threads”. So I see that gives me a better results with memory, but is it possible that conversion causes execution time increase? Or its just may be my wrong way of implementing them
    r
    s
    +2
    • 5
    • 5
  • k

    kawmra

    04/24/2019, 7:02 AM
    Hello. I have a question about combining coroutines and
    Result<T>
    . I have the code like following:
    launch {
        runCatching { doSomething() }
            .onSuccess {
                doSuccessProcess(it)
            }
            .onFailure {
                doFailureProcess()
            }
    }
    I wanna handle errors if
    doSomething()
    fails. But this code catches
    CancellationException
    as well when
    launch
    was canceled. Are there any problems? Can I just ignore the
    CancellationException
    ?
    g
    • 2
    • 12
  • j

    jw

    04/24/2019, 1:11 PM
    just(1, 2, 3)
    ->
    flowOf(1, 2, 3)
    error(Exception())
    ->
    flow { throw Exception() }
    😍 1
    t
    l
    • 3
    • 10
  • a

    addamsson

    04/25/2019, 12:51 PM
    I'm reading the docs about `Channel`s and I was a bit puzzled. In the Fan-out examples it uses extension functions on
    CoroutineScope
    , but in the Fan-in examples it uses suspending functions. Is there a practical difference between these two approaches? ---->
    @JvmStatic
        fun main(args: Array<String>) = runBlocking {
    
            val channel = Channel<String>()
            launch { sendString(channel, "foo", 200L) }
            launch { sendString(channel, "BAR!", 500L) }
            repeat(6) {
                // receive first six
                println(channel.receive())
            }
            coroutineContext.cancelChildren() // cancel all children to let main finish
    
        }
    
        suspend fun sendString(channel: SendChannel<String>, s: String, time: Long) {
            while (true) {
                delay(time)
                channel.send(s)
            }
        }
    versus
    @JvmStatic
        fun main(args: Array<String>) = runBlocking {
    
            val channel = Channel<String>()
            sendString(channel, "foo", 200L)
            sendString(channel, "BAR!", 500L)
            repeat(6) {
                // receive first six
                println(channel.receive())
            }
            coroutineContext.cancelChildren() // cancel all children to let main finish
    
        }
    
        fun CoroutineScope.sendString(channel: SendChannel<String>, s: String, time: Long) = launch {
            while (true) {
                delay(time)
                channel.send(s)
            }
        }
    Both are doing the same if I understand the concepts correctly and also produce the same output. When should I use which?
    m
    • 2
    • 6
  • z

    Zach Klippenstein (he/him) [MOD]

    04/25/2019, 5:29 PM
    Does anyone know why the
    produce
    builder doesn’t take a
    CoroutineStart
    parameter? (cc @elizarov)
    e
    • 2
    • 3
  • m

    marcoferrer

    04/25/2019, 6:27 PM
    Im having a hard time illustrating cooperative cancellation to users of my library. I tried taking a shot at putting together a diagram but I feel like its not very clear. Does anyone know of any good resources to illustrate this? If not, Im open to any suggestions for improving this diagram.
    k
    • 2
    • 1
  • m

    marcoferrer

    04/25/2019, 6:28 PM
    😍 1
    d
    g
    • 3
    • 3
  • s

    spierce7

    04/25/2019, 7:38 PM
    Im using the following, and It doesn't seem to be removing the warnings from my project. Can anyone suggest an alternative?
    tasks.withType(org.jetbrains.kotlin.gradle.tasks.KotlinCompile) {
                kotlinOptions.freeCompilerArgs += ["-Xuse-experimental=kotlinx.coroutines.ExperimentalCoroutinesApi"]
            }
    g
    • 2
    • 3
  • s

    streetsofboston

    04/25/2019, 8:53 PM
    I am wondering about handling exceptions (throwables) in this example:
    val xHandler = CoroutineExceptionHandler { c, e ->
        println("Handled Crash in coroutine $c")
        e.printStackTrace(System.out)
    }
    
    fun launch_handleExceptionInCoroutineExceptionHandler(): Unit = runBlocking(xHandler) {
        launch(<http://Dispatchers.IO|Dispatchers.IO> + xHandler) {
            delay(1000)
            throw Exception("Some Exception 1")
        }
        delay(2000)
    }
    
    fun main() {
        Thread.setDefaultUncaughtExceptionHandler { t, e ->
            println("App Crash in thread $t")
            e.printStackTrace(System.out)
        }
        launch_handleExceptionInCoroutineExceptionHandler()
    }
    The
    xHandler
    is never called. The output is produced by the default-uncaught-exception-handler instead. I expected the
    xHandler
    to be called. If I provide another scope to the
    launch
    , eg
    GlobalScope.launch { ... }
    it works as expected and the
    xHandler
    is called. Why is the
    xHandler
    not called when using the `runBlocking`’s scope? (just to be sure, I provided the
    xHandler
    in 2 places, when calling
    runBlocking
    and when calling `launch`…)
    e
    • 2
    • 11
  • s

    simon.vergauwen

    04/26/2019, 7:52 AM
    If I have a
    java.util.concurrent.ThreadPoolExecutor
    with a keepAlive of 0, will it respect that
    keepAlive
    as a
    CoroutineContext
    ?
    v
    • 2
    • 6
  • v

    Vsevolod Tolstopyatov [JB]

    04/26/2019, 8:44 AM
    📣 📣 📣
    kotlinx.coroutines
    1.2.1 is here! Changelog: • Infrastructure for testing coroutine-specific code in
    kotlinx-coroutines-test
    (read more here https://github.com/Kotlin/kotlinx.coroutines/tree/master/kotlinx-coroutines-test#runblockingtest). Thanks Sean McQuillan for the contribution! •
    Job.asCompletableFuture
    extension in jdk8 module • New operators in `Flow`:
    switchMap
    ,
    debounce
    ,
    sample
    • Various fixes and improvements, full changelog: https://github.com/Kotlin/kotlinx.coroutines/releases/tag/1.2.1
    👍🏼 2
    :kotlin: 4
    👍 2
    👏🏾 3
    😒uspend: 5
    🎉 18
    ❤️ 5
    l
    • 2
    • 1
  • a

    altavir

    04/26/2019, 10:50 AM
    Is there a way to make a transformation of Flow with a statefull collector? I am migrating kmath streaming API to flow and I need to implement a chunking and windowing operation (take
    n
    subsequent elements and join them into one).
    m
    • 2
    • 2
  • a

    altavir

    04/26/2019, 11:25 AM
    Another question. It is probably somewhere in the documentation, but is the
    Flow
    map operation parallelizable?
    g
    e
    s
    • 4
    • 22
  • a

    altavir

    04/26/2019, 2:59 PM
    Here is my implementation based on
    flowOn
    . I am not sure I've done context switching correctly. And I can't use internal functions like
    getCancellationException
    for proper exception propagation. I will open a ticket for this.
    Parallel_map_for_Flow.kt
    d
    • 2
    • 3
  • a

    Andrew Gazelka

    04/26/2019, 10:44 PM
    I have a system where I have multiple `Resource`s where only one process (coroutine) should be able to access it at a time. The main function of a
    Resource
    is
    suspend fun take(priority: Int = 0, immediate: Boolean = false)
    where a task with a lower priority will be scheduled first and higher later. The
    immediate
    argument will determine whether the currently executing process should be interrupted if
    take(...)
    has a lower priority than the currently executing task. A resource is given back with
    Resource#giveBack()
    . Any recommendations on how I could do this idiomatically?
    d
    • 2
    • 6
  • l

    Lulu

    04/27/2019, 12:43 AM
    I'm trying to implement an ideal ratelimiting system with coroutines. Basically, I want to send requests to the server, and if it told me that I'm being ratelimited, requests should be delayed till the ratelimit is over. All this while also returning responses in time (we don't wait for all requests to finish, and provide the response to the caller whenever it comes). I already have an implementation but it's far from ideal. What's the best way to do this?
    d
    • 2
    • 1
  • e

    efemoney

    04/27/2019, 11:11 AM
    Is there an equivalent for
    Thread.UncaughtExceptionHandler
    with `CoroutineExceptionHandler`s that is a globally handled exception handler?
    d
    t
    • 3
    • 5
  • a

    ansman

    04/27/2019, 3:12 PM
    Do I need to keep a strong reference to a continuation given to me in
    suspendCancellableCoroutine
    ? I need to work around a memory leak and I was planning on doing that by keeping a weak ref to the continuation
    d
    l
    b
    • 4
    • 7
  • a

    altavir

    04/28/2019, 6:47 AM
    While experimenting with parallel flow extensions, I found a not so obvious behavior. This code:
    val deferred = coroutineScope {
                    async(start = CoroutineStart.LAZY) { println("async") }
                }
                deferred.await()
    causes a infinite block. I understand that it is caused by interference of lazy deferred with structured concurrency, but it significantly reduces application for lazy deferred. Is it intended to be this way?
    👆 1
    o
    d
    l
    • 4
    • 9
  • l

    littlelightcz

    04/28/2019, 8:58 AM
    I am testing Flow with Observables, having this code:
    runBlocking(<http://Dispatchers.IO|Dispatchers.IO>) {
            val myList = mutableListOf(1).asObservable()
    
            launch {
                myList.asFlow().collect { println("A $it") }
            }
    
            delay(1000)
    
            myList += 2
    
            launch {
                myList.asFlow().collect { println("B $it") }
            }
    
            delay(1000)
        }
    Which produces:
    A 1
    B 1
    B 2
    Is there some sort of non-terminal
    collect
    yet that would listen for further changes, so that I would see
    A 2
    in the output when
    myList
    gets updated?
    z
    • 2
    • 7
  • h

    halim

    04/28/2019, 9:19 AM
    hi
    i am confuse with this syntax 
    fun task(bloc: suspend () -> Unit) { .... }
    what does mean call suspend function inside regular function ?
    o
    s
    g
    • 4
    • 23
  • p

    Paul Woitaschek

    04/29/2019, 3:17 PM
    I want to create a suspending function that calls
    startActivityForResult
    and it suspends until
    onActivityResult
    is called. Is using a Channel the right way to do that?
    kotlin
    class MyActivty : Activity(){
    
      private val channel = Channel<Uri>()
    
      override fun onActivityResult(data: Intent){
        val uri = data.data
        channel.offer(uri)
      }
    
    
      suspend fun soSthWithStartActivtyForResult() : Uri {
         startActivityForResult(intent, 42)
         return channel.receive()
      }
    }
    s
    n
    +3
    • 6
    • 13
  • s

    streetsofboston

    04/29/2019, 4:05 PM
    val xHandlerParent = CoroutineExceptionHandler { c, e ->
        println("Parent Handled Crash")
    }
    
    val xHandlerLeaf = CoroutineExceptionHandler { c, e ->
        println("Leaf Handled Crash")
    }
    
    fun main() {
        CoroutineScope(xHandlerParent).launch(xHandlerLeaf) {
            delay(1000)
            throw Exception("Some Exception 1")
        }
    
        Thread.sleep(2000)
    }
    prints out
    Leaf Handled Crash
    . However, I expected the output to be
    Parent Handled Crash
    , because an exception bubbles up to the top-most parent and
    CoroutineExceptionHandler
    of that top-most parent should be used. If I replace
    CoroutineScope(xHandlerParent). ...
    with
    runBlocking { ... }
    , the
    xHandlerLeaf
    is not used, as I expected, because the top-most parent is used and that is a scoped-parent that just throws the exception up the call-stack. I’m not sure if this is a bug or if I don’t understand how exceptions are handled 🙂
    y
    m
    • 3
    • 7
Powered by Linen
Title
s

streetsofboston

04/29/2019, 4:05 PM
val xHandlerParent = CoroutineExceptionHandler { c, e ->
    println("Parent Handled Crash")
}

val xHandlerLeaf = CoroutineExceptionHandler { c, e ->
    println("Leaf Handled Crash")
}

fun main() {
    CoroutineScope(xHandlerParent).launch(xHandlerLeaf) {
        delay(1000)
        throw Exception("Some Exception 1")
    }

    Thread.sleep(2000)
}
prints out
Leaf Handled Crash
. However, I expected the output to be
Parent Handled Crash
, because an exception bubbles up to the top-most parent and
CoroutineExceptionHandler
of that top-most parent should be used. If I replace
CoroutineScope(xHandlerParent). ...
with
runBlocking { ... }
, the
xHandlerLeaf
is not used, as I expected, because the top-most parent is used and that is a scoped-parent that just throws the exception up the call-stack. I’m not sure if this is a bug or if I don’t understand how exceptions are handled 🙂
y

yousefa2

04/29/2019, 4:07 PM
Your
xHandlerLeaf
handles the exception which stops it from propagating to it's parent. That's why you don't get it in the parent.
s

streetsofboston

04/29/2019, 4:08 PM
But if I do:
fun main() {
    runBlocking{ 
        launch(xHandlerLeaf) {
            delay(1000)
            throw Exception("Some Exception 1")
        }
    }
    Thread.sleep(2000)
}
the
xHandlerLeaf
is not used.
According to Roman: https://kotlinlang.slack.com/archives/C1CFAFJSK/p1556289120231200?thread_ts=1556225617.217800&amp;cid=C1CFAFJSK and https://kotlinlang.slack.com/archives/C1CFAFJSK/p1556289713232000?thread_ts=1556225617.217800&amp;cid=C1CFAFJSK It bubbles up to the top-most parent and the
CoroutineExceptionHandler
of that parent is used.
When I change the example to this, the
xHandlerParent
does handle the exception, as I expect:
fun main() {
    CoroutineScope(Dispatchers.Default).launch(xHandlerParent) {
        launch(xHandlerLeaf) {
            delay(1000)
            throw Exception("Some Exception 1")
        }
    }

    Thread.sleep(2000)
}
m

Martín Ickowicz

04/29/2019, 7:25 PM
as far I know the
CoroutineExceptionHandler
consumes the exception and does not propagates it in your last example you are throwing a new exception, which is caught by the parent scope
s

streetsofboston

04/29/2019, 7:32 PM
I created an issue for this 🙂 https://github.com/Kotlin/kotlinx.coroutines/issues/1157
👍 1
m

Martín Ickowicz

04/29/2019, 7:37 PM
👍
View count: 3