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

    Daniele Segato

    09/15/2022, 9:56 AM
    is there any particular reason why
    flatMapLatest
    and
    transformLatest
    are still marked with
    @ExperimentalCoroutinesApi
    ?
    e
    • 2
    • 2
  • b

    Bradleycorn

    09/15/2022, 1:19 PM
    Hi all. Wanted to see if I’m using
    join
    in a proper manner and/or if there is a better way to do what I’m doing. I’m launching a coroutine that does some work (makes a few HTTP requests). Then later, in response to some event, I need to launch another coroutine to do some different work. When the 2nd coroutine is launched, I want to make sure the first coroutine is finished before the 2nd one does its work (it’s also ok if the first one was never launched at all). To accomplish this, I’m keeping a reference to the
    Job
    from the first coroutine, and calling its
    join()
    method from the second coroutine. A code sample is included in the 🧵 Two questions: 1. Is it OK to do it this way, or are there any problems with it? 2. Is there some better/more efficient way to do it?
    e
    • 2
    • 3
  • o

    oday

    09/16/2022, 5:29 PM
    Hello, so I am wondering about this piece of code
    private fun startCoroutines() {
        GlobalScope.launch(Dispatchers.Main) {
            withTimeout(1000L) {
                println("This is executed before the first delay")
                stallForTime()
                println("This is executed after the first delay")
            }
    
            printAfterSomething("the timeout")
        }
    
        println("This is executed immediately")
    }
    
    suspend fun stallForTime() {
        withContext(Dispatchers.Default) {
            delay(2000L)
        }
    }
    after the child job inside
    withTimeout
    does not finish in time (because stallForTime made it take too long (2 seconds)) why does the
    printAfterSomething
    not get called
    j
    • 2
    • 8
  • c

    Chuck Stein

    09/17/2022, 4:55 AM
    In a suspend function is it possible to launch a coroutine with the current scope and return immediately? The
    coroutineScope
    function waits for the block's completion before returning, but I want to just
    launch
    something with the current scope, fire and forget
    j
    e
    +2
    • 5
    • 24
  • p

    PHondogo

    09/18/2022, 7:26 AM
    Hello! What is the best way to handle cancellation excaptions? If silently rethrow them, can miss real exception. If catch - normal cancellation will be treated as exception.
    b
    e
    • 3
    • 2
  • o

    oday

    09/18/2022, 5:33 PM
    so I would like to inject this usecase that I have which returns the Result class, and the method to do that is suspendable so i am using
    runTest{ }
    to call it, but this is causing me to be unable to answer with the type that I want now, since it’s now expecting
    TestResult
    , I want to return
    Result.success(obj)
    @ExperimentalCoroutinesApi
    @Inject
    fun firebaseSignInWithEmail(mock: FirebaseSignInWithEmail) {
        every {
            runTest {
                mock.invoke("anyEmail", "anyPassword")
            }
        } returns TestResult
    }
    f
    • 2
    • 3
  • c

    Christopher Porto

    09/19/2022, 5:29 PM
    Hello, I have a hot flow (MutableSharedFlow) and was wondering why I'm required to launch a new coroutine from a new scope when calling collect for the logic to continue? e.g
    suspend fun func1() = CoroutineScope(Dispatchers.Default).launch {
        func2()
        println("Not called")
    }
    suspend fun func2() = coroutineScope {
        launch {
            someFlow.collect { logic.invoke(it) }
        }
    }
    e
    c
    • 3
    • 6
  • b

    Ben Kosten

    09/19/2022, 7:42 PM
    Hey guys, I'm writing a low latency TCP proxy using
    java.nio.AsynchronousSocketServerChannel
    and I'm using coroutine channels to push my data to a
    writerChannel
    which is responsible for forwarding the data between a client and server. I'm noticing some start delays between when I push data to my channel and when its consumer actually starts. my code looks like something of the following
    //inside the ReadHandler future, push the data read from the socket each time the future completes, also record the start time
    val startTime = System.nanoTime()
    writerChannel.trySendBlocking(Pair(data, startTime))
    
    //somewhere else in the codebase, consume the data from the channel
    scope.launch(Dispatchers.Unconfined) {
        writerChannel.consumeEach { (data, startTime) ->
            val startElapsed = (System.nanoTime() - startTime) / 1_000_000
            println("Took: ${startElapsed}ms to start!")
    
            //do some other stuff with the data
        }
    }
    In one of my tests, I open up 200 simultaneous connections, and every now and then it looks like a coroutine has a cold start of about (2-4)ms with some outliers of upwards of 8ms. Is there any way how I can reduce the amount of time it takes a coroutine to start like that?
  • r

    Rihards

    09/20/2022, 12:16 PM
    Hi! I’m working on multiplatform project where I need to update all my libraries. On CI I received
    There is no event loop. Use runBlocking { ... } to start one
    so I changed coroutine version to
    1.6.3-native-mt
    . Now the issue is that many other dependencies does not use multithreaded coroutines and I receive errors - is there any way I can force them in my Android project to use this specific version?
    l
    • 2
    • 2
  • j

    João Gabriel Zó

    09/20/2022, 12:42 PM
    Is there a functioning Kafka lib that works well with coroutines? Nothing fancy, just need to send some messages to my notifications service
    s
    h
    • 3
    • 14
  • r

    reactormonk

    09/20/2022, 4:00 PM
    I've got a rather callback-heavy API, which I've modeled roughly as
    fun onReaderConnected(): Flow<Reader> { ... }
    class Reader {
      fun onCard(): Flow<Card>
    }
    And I'm consuming it via
    onReaderConnected() { reader ->
      reader.onCard().collect {
        ... process card ...
      }
    }
    Now I've run into the issue where the reader disconnects, the inner
    collect
    won't stop, so the new reader connection won't get activated. How do I best model that?
    s
    l
    • 3
    • 4
  • o

    oday

    09/21/2022, 12:08 PM
    literally just that last field
    h
    n
    • 3
    • 27
  • s

    Sam

    09/22/2022, 9:31 AM
    Because the code inside
    collect
    is actually run as part of the call to
    emit
    . Use the
    catch
    operator instead if you don’t want that behaviour (I think…)
    d
    l
    +2
    • 5
    • 9
  • l

    Lukas Lechner

    09/22/2022, 1:01 PM
    What are use cases for the
    .cancellable()
    flow operator?
    c
    • 2
    • 1
  • r

    reactormonk

    09/23/2022, 12:35 PM
    I've got a
    Flow
    which I'm running
    collectLatest()
    on, but it's only firing the first time I send something into it, not the second time... what can be the reasons here?
    t
    l
    • 3
    • 8
  • m

    Mikael Ståldal

    09/25/2022, 8:48 AM
    I am learning Kotlin by reading the Programming Kotlin book. In the section about coroutine cancellations (page 319-320), it suggest to wrap long running blocking code with
    async { doStuff() }.await()
    to make the coroutine cancellable (see
    code/async/cancelandsuspension.kts
    in https://media.pragprog.com/titles/vskotlin/code/vskotlin-code.zip). Is that really a good advice? It seems like the long running blocking code is not cancelled, it is simply detached from the parent coroutine and will continue to run to completion in backround, and will block the completion of the surrounding
    runBlocking
    .
    fun getResponse(ms: Int): String {
        val s = URL("<http://httpstat.us/200?sleep=$ms>").readText()
        println("${LocalTime.now()} Got: $s")
        return s
    }
    
    suspend fun fetchResponse() = coroutineScope {
        try {
            println(async { getResponse(4000) }.await())
        } catch (ex: CancellationException) {
            println("${LocalTime.now()} fetchResponse: ${ex.message}")
        }
    }
    
    fun main() {
        println("${LocalTime.now()} before runBlocking")
        runBlocking {
            val job = launch(Dispatchers.Default) {
                launch { fetchResponse() }
            }
    
            println("${LocalTime.now()} Let it run...")
            delay(2000)
            println("${LocalTime.now()} OK, that's enough, cancel")
            job.cancel()
            println("${LocalTime.now()} end of runBlocking")
        }
        println("${LocalTime.now()} after runBlocking")
    }
    u
    e
    • 3
    • 6
  • c

    chanjungskim

    09/25/2022, 6:03 PM
    Can anybody answer this? : https://stackoverflow.com/questions/73846708/what-does-coroutinecontext-do
  • d

    dimsuz

    09/26/2022, 12:08 PM
    Is it a good practice for library (or any generic API) to return
    StateFlow
    or
    SharedFlow
    if the particular flow behaves state-like or share-like? Or is it better to stick to
    Flow
    to be more generic? I was advised to do the latter, but oftentimes I find it useful to do something like
    onSubscription
    which is unavailable for
    Flow
    and having to do
    stateIn
    /
    shareIn
    when I know that underlying code already has `StateFlow`/`SharedFlow` somehow feels wasteful.
    r
    • 2
    • 4
  • g

    Gomathi Gms

    09/27/2022, 3:49 PM
    Team #coroutines, is jobCencellationException in flow coroutines is common or how can we avoid this exception
    g
    c
    • 3
    • 3
  • d

    dimsuz

    09/27/2022, 5:46 PM
    Why does the following
    val shared = MutableSharedFlow<Int>()
    merge(
      shared.onSubscription { shared.emit(3) },
      flowOf(100,200,300),
    ).collect {
      println("$it")
    }
    never prints
    3
    , only
    100 200 300
    ? And is there a way to setup this so that I have some point where it is safe to post to
    shared
    to guarantee delivery to
    collect
    ?
    a
    n
    • 3
    • 3
  • w

    wakingrufus

    09/27/2022, 10:10 PM
    I just got into a heated discussion with someone who claimed kotlin coroutines are nothing like project loom virtual threads because they don't copy the call stack. I suspect he is wrong, because coroutines seem to behave just like loom virtual threads to me, but I don't know enough. Can someone enlighten me?
    d
    z
    • 3
    • 9
  • m

    Matteo Mirk

    09/29/2022, 7:37 AM
    Hello, in a project we needed to replicate a functioning block of coroutine code we had in similar functions (the one inside
    also { }
    ), to send an event before calling a service. We came up with this, but I think it’s ugly and was wondering if it could be simplified:
    override suspend fun validateCart(request: ValidateCartRequest): ValidateCartResponse {
            supervisorScope {
                launch(Dispatchers.Unconfined) {
                    domainEventsPublisher.publishCartValidationSubmitted(request.cartId)
                }
            }
            return super.validateCart(request).also { response ->
                supervisorScope {
                    launch(Dispatchers.Unconfined) {
                        if (response.isValid) domainEventsPublisher.publishCartValidationSucceeded(response)
                    }
                }
            }
        }
    can i wrap everything in a single supervisorScope? Would it be equivalent to this code?
    s
    • 2
    • 11
  • g

    George

    09/29/2022, 8:25 AM
    Hi folks, i browsed kotlinx.coroutines lib and i have a question about package structure: all flow operators even though they are in separate file their package is still
    package kotlinx.coroutines.flow
    . I guess this is for easier discover-ability?. I am wondering if i can use also this pattern when i seem fit in my application code or it is not recommended at all.? Thanks in advance for any help and answers ! Also how come the intelij warning is not suppressed (@file:Suppress("PackageDirectoryMismatch"))? Does not that lead to confusion if the package is intentional or not ?
    s
    • 2
    • 10
  • z

    Zoltan Demant

    09/29/2022, 9:37 AM
    Id love to understand why this piece of code becomes unresponsive when a lot of work is already being done in the background. 🧵
    s
    j
    r
    • 4
    • 14
  • n

    Norbi

    09/29/2022, 5:02 PM
    Maybe do you have some info about planned support for Java 19 virtual threads and
    ExtentLocal
    (in the foreseeable future)? Thanks.
  • b

    bbaldino

    09/30/2022, 4:50 PM
    Is there a mechanism similar to
    Semaphore
    that has no available 'permits' to start? I need to launch a coroutine to keep a scope alive, but have it suspend until something else tells it to "go"
    c
    e
    • 3
    • 6
  • n

    natario1

    09/30/2022, 4:54 PM
    Given a job
    job
    that was cancelled, cancellation could have been generated either from within
    job
    (e.g. with
    job.cancel
    , or one of its descendants) or by some parent job up the hierarchy. Is there any way to disambiguate between these two cases? I saw that
    JobCancellationException
    has a nice
    job
    field, but it’s not public.
  • j

    John Herrlin

    10/01/2022, 11:46 AM
    Hey! Just got a job where we use Kotlin and Spring. Currently reading “Kotlin Coroutines” by Marcin and it gives good insights. Looking for books or resources (no tutorials) to learn more about Kotlin + Spring + Flow. Thx ❤️
  • c

    Choi

    10/02/2022, 3:17 AM
    It says `The CoroutineDispatcher that is designed for offloading blocking IO tasks to a shared pool of threads`in the comments of
    <http://Dispatchers.IO|Dispatchers.IO>
    . What does
    offloading
    mean here?
    k
    • 2
    • 1
  • l

    Lukas Lechner

    10/03/2022, 8:52 AM
    How can I cancel flow collection from within the
    collect{}
    operator? The docs say that it should be possible to call
    cancel()
    , but that doesn’t seem to work….
    s
    r
    j
    • 4
    • 7
Powered by Linen
Title
l

Lukas Lechner

10/03/2022, 8:52 AM
How can I cancel flow collection from within the
collect{}
operator? The docs say that it should be possible to call
cancel()
, but that doesn’t seem to work….
s

simon.vergauwen

10/03/2022, 8:56 AM
Where is the
cancel()
coming from in that case? 🤔
throw CancellationException
is the first thing that comes to mind, which then probably ends up in a
launch
or
launchIn
and then the behavior depend on the surrounding
CoroutineScope
impl. What is your use-case for this?
l

Lukas Lechner

10/03/2022, 9:03 AM
Ahh, okay, the docs use
runBlocking{}
, and there we have
coroutineScope
as receiver, on which cancel can be called.
https://kotlinlang.org/docs/flow.html#flow-cancellation-checks
However I wonder why there is a crash in this case when a
CancellationException
is thrown 🤔 Aren’t
CancellationExceptions
special kind of exceptions that don’t lead to crashes?
r

Robert Williams

10/03/2022, 9:10 AM
runBlocking needs to throw because it can return a result which won't be available if the coroutine is cancelled
j

Jhonatan Sabadi

10/04/2022, 11:17 AM
It's important to cancel and use "ensureactive" on the emitter, if you don't do that, you can cancel and flow still send
s

simon.vergauwen

10/04/2022, 11:19 AM
You can also compose this after the fact by calling
cancellable
it will inject
ensureActive()
in between calls to
emit
. https://kotlinlang.org/api/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.flow/cancellable.html
View count: 9