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

    Advitiay Anand

    04/14/2022, 9:37 AM
    Noob level question: What is the difference between suspend functions and normal functions when calling from a coroutine? I mean, even if you call normal functions, they still run asynchronously, right?
    j
    m
    +2
    • 5
    • 21
  • d

    Dazai

    04/14/2022, 10:36 AM
    sometimes my app throws one of these stacktraces without any references to anywhere in my code, how would i even go about debugging this? thanks!
    java.lang.NegativeArraySizeException: -1537060379
    at <http://io.ktor.utils.io|io.ktor.utils.io>.core.StringsKt.readBytes(Strings.kt:165)
    at <http://io.ktor.utils.io|io.ktor.utils.io>.core.StringsKt.readBytes$default(Strings.kt:162)
    at io.ktor.client.call.SavedCallKt.save(SavedCall.kt:73)
    at io.ktor.client.call.SavedCallKt$save$1.invokeSuspend(SavedCall.kt)
    at kotlin.coroutines.jvm.internal.BaseContinuationImpl.resumeWith(ContinuationImpl.kt:33)
    at kotlinx.coroutines.DispatchedTask.run(DispatchedTask.kt:106)
    at kotlinx.coroutines.internal.LimitedDispatcher.run(LimitedDispatcher.kt:39)
    at kotlinx.coroutines.scheduling.TaskImpl.run(Tasks.kt:95)
    at kotlinx.coroutines.scheduling.CoroutineScheduler.runSafely(CoroutineScheduler.kt:571)
    at kotlinx.coroutines.scheduling.CoroutineScheduler$Worker.executeTask(CoroutineScheduler.kt:750)
    at kotlinx.coroutines.scheduling.CoroutineScheduler$Worker.runWorker(CoroutineScheduler.kt:678)
    at kotlinx.coroutines.scheduling.CoroutineScheduler$Worker.run(CoroutineScheduler.kt:665)
    s
    c
    • 3
    • 14
  • t

    Tower Guidev2

    04/14/2022, 11:58 AM
    Hi i need to unit test some code that employs
    GlobalScope
    is there a Best Practice approach?
    s
    u
    • 3
    • 16
  • r

    Remon Shehata

    04/14/2022, 12:06 PM
    How to make suspend function synchronized (thread-safe)?
    t
    g
    +2
    • 5
    • 16
  • d

    Dazai

    04/15/2022, 10:55 AM
    I have a MutableStateFlow<String> which passes an argument to a suspend fun. On each latest one I want to launch a suspend fun on the IO dispatcher, however if it emits a new value before the previous suspend function is complete, it should cancel that one and launch the suspend fun with the new argument. How should I do this?
    i
    • 2
    • 2
  • m

    MBegemot

    04/15/2022, 1:59 PM
    In the context of android and compose I found out that when using runBlocking() if I use a dispatcher parameter on it (any of them), if the code inside runBlocking or in any of the called functions does contain a delay() of any size the main tread will be blocked for ever . It took me two days to sort it out!!!
    a
    • 2
    • 1
  • e

    Exerosis

    04/15/2022, 5:09 PM
    Might be a silly question but what's the reason get and set operators can't be suspending?
    e
    • 2
    • 3
  • u

    ursus

    04/18/2022, 12:25 AM
    Hi, I’m trying to create a stories ui progressbar I’d best like to have that progress logic in a view model and keep the view dumb I looked into android ValueAnimator source, and its basically driven by Handler ticks What would be best to emulator this in coroutines/flow? Would this do it reliably?
    while(true) {
    	yield() <--- In practise it seems yield emulates <http://Handler.post|Handler.post>
    	emit(Unit)
    }
    Or should I just wrap the ValueAnimator as Flow and call it a day?
    a
    • 2
    • 27
  • u

    ursus

    04/18/2022, 1:13 AM
    private var running = true
    
    scope.launch {
        flow {
            var counter = 0
            while (true) {
                Log.d("Default", "waiting...")
                while (running) {
                    delay(200)
                    emit(counter++)
                }
            }
        }
            .collect {
                Log.d("Default", "value=$it")
            }
    }
    
    fun pause() {
        running = false
    }
    
    fun resume() {
        running = true
    }
    how would I best implement pausing/resuming, without spamming “waiting…” when
    running == false
    ? i.e make it suspend and not retry the while condition so fast?
    :thread-please: 1
    d
    • 2
    • 1
  • v

    Vlad

    04/18/2022, 1:04 PM
    👋 I am trying to migrate some of the tests from
    coroutines-test:1.5
    to 1.6.1 and can’t wrap my head around some of the new behaviours. In 1.6 we seemingly have lost the ability to control the dispatch of individual dispatchers used internally by the classes under test, since all of the test dispatchers have to use a shared
    TestCoroutineScheduler
    that now is the owner of the shared virtual time. More details in the thread.
    a
    • 2
    • 3
  • u

    ursus

    04/18/2022, 10:01 PM
    fun ProgressThingy(duration: Long, running: Flow<Boolean>): Flow<Float> {
        return callbackFlow {
            val animator = ValueAnimator.ofFloat(0F, 1F)
            animator.duration = duration
            animator.addUpdateListener {
                trySend(it.animatedFraction)
            }
            animator.addListener(onCancel = {
                cancel()
            })
            animator.start()
    
            running.collect {
                if (it) animator.resume() else animator.pause()
            }
    
            awaitClose {
                animator.cancel()
            }
        }
    }
    does anyone see a problem with collecting the running signal like that within the callback flow scope? it appears to work fine
    j
    • 2
    • 17
  • s

    simon.vergauwen

    04/19/2022, 10:26 AM
    Hey everyone, Is it expected that
    Flow#flatMapMerge
    or any of the other concurrent
    Flow
    operator swallows
    CancellationException
    . Two examples in the thread.
    ✅ 1
    j
    • 2
    • 11
  • w

    William Reed

    04/19/2022, 6:37 PM
    I have a 'parent'
    CoroutineScope
    which has a long lifecycle. I want to make another scope which has a shorter lifecycle (potentially several in the same span as the 'parent'). If the parent scope is cancelled I want both parent and the shorter lifecycle scope to be cancelled as far as i can tell you can't inherit scopes like this. another (seemingly bad) idea I have is to maintain a collection of `Job`s for the shorter lifecycle group, which will allow me to cancel everything in that collection, or if the parent scope is cancelled, they would all be launched under it anyway, and get cancelled
    j
    z
    • 3
    • 8
  • r

    Remon Shehata

    04/20/2022, 4:28 PM
    is there a difference between: 1- calling a normal function from a coroutine scope
    fun foo(){ // do something}
    coroutineScope.launch{ foo }
    2 - calling suspend function from a coroutine scope
    suspend fun foo(){ // do something}
    coroutineScope.launch{ foo }
    h
    • 2
    • 1
  • j

    julian

    04/21/2022, 12:32 AM
    It seems like it is no longer the case that a
    CoroutineExceptionHandler
    installed on a top-level/root
    launch
    coroutine builder will catch uncaught exceptions. That's what I found with coroutines
    1.6.1
    . The handler must be installed on the
    CoroutineScope
    itself. Just want to sanity check that this is actually the case, not something weird that I'm doing and not realizing. Here's sample code of what used to catch, but seems to no longer:
    fun main() {
    
        val coroutineExceptionHandler = CoroutineExceptionHandler { coroutineContext, exception ->
            println("Handle $exception in CoroutineExceptionHandler")
        }
    
        val topLevelScope = CoroutineScope(Job())
    
        topLevelScope.launch {
            launch(coroutineExceptionHandler) {
                throw RuntimeException("RuntimeException in nested coroutine")
            }
        }
    
        Thread.sleep(100)
    }
    d
    • 2
    • 2
  • a

    Ayfri

    04/21/2022, 12:52 PM
    Simple question before I dug into it, does coroutines works on Kotlin/JS ?
    j
    j
    +2
    • 5
    • 13
  • c

    cah

    04/21/2022, 3:38 PM
    Why does this not work?
    fun CoroutineScope.launchIO(block: suspend CoroutineScope.() -> Unit): Job {
        return launch(
            context = IO,
            start = CoroutineStart.DEFAULT,
            block = block
        )
    }
    If I try to use this in place of the regular launch I get the following error:
    java.lang.NoSuchMethodError: 'kotlinx.coroutines.Job com.some.misc.ExtensionsKt.launchIO(kotlinx.coroutines.CoroutineScope, kotlin.jvm.functions.Function2)'
    I am more curious as to what I'm missing here rather than this being a serious use case
    j
    j
    • 3
    • 4
  • c

    Chris Fillmore

    04/21/2022, 4:16 PM
    I have this method. It sends a message out over a websocket and waits for a reply.
    suspend fun sendAndWait(message: Message): Message = withTimeout(5000) {
      launch {
        send(message)
      }
      // 'incoming' is a Flow<Message>
      incoming.first { /* logic here which matches outbound messages with inbound ones by some matching id */ }
    }
    The timeout never works. It never times out, I don’t get an exception. There are two suspension points:
    send(message)
    and
    incoming.first { }
    . Is there something I’m misunderstanding about timeouts?
    withTimeout
    has otherwise worked for me; I’m not sure what’s different in this case. Any ideas?
    j
    s
    j
    • 4
    • 11
  • r

    Ridwan Farouki

    04/23/2022, 10:03 PM
    How does one get a manually created
    CoroutineScope
    to use a `TestScope`'s scheduler in
    kotlinx-coroutines-test:1.6.1
    for the virtual time behaviour? I would have expected
    CoroutineScope(Job() + testScheduler)
    to work but it doesn't. (Note that
    CoroutineScope(Job() + coroutineContext)
    does work but then when I try to cancel
    differentScope
    it fails the test because it cancels the parent
    TestScope
    , making it hard to test code that uses structured concurrency)
    fun tickTest() = runTest {
            val differentScope = CoroutineScope(Job() + testScheduler)
    
            val ticks = mutableListOf<Int>()
    
            val tickJob = differentScope.launch {
                var time = 0
                while (true) {
                    delay(1_000)
                    ticks.add(++time)
                }
            }
    
            advanceTimeBy(5_001)
    
            tickJob.cancel()
    
            println(ticks)
            assert(ticks.size == 5)
        }
    j
    d
    • 3
    • 6
  • g

    Grouvie

    04/24/2022, 5:16 PM
    Hello. I have a question whether coroutines are suitable for my application.
    j
    d
    c
    • 4
    • 7
  • c

    Colton Idle

    04/26/2022, 8:39 PM
    I'm using firebase firestore to make a query on my application start. I actually am making 4 simulataneous queries. But 1 of them fails and I get a stacktrace that's unhelpful in terms of finding which of my 4 queries is the culprit. I think it's because I'm using a coroutine? Here is my code
    fun doThing() {
      viewModelScope.launch {
        repository.getDocument()
    ...
    suspend fun getDocument() {
      return FirebaseFirestore.getInstance()
          .collection("mycollec")
          .document("mydoc")
          .get()
          .await()
          .toObject<MyDoc>()
    }
    Any idea why the stacktrace I get doesn't point to the code above at all?
    r
    j
    r
    • 4
    • 7
  • t

    Trey

    04/27/2022, 2:16 PM
    Can somebody help me understand why I'm getting "kotlinx.coroutines.JobCancellationException: Parent job is Completed" when I try to start my web service in my view model? I'm trying to delay the connection until after I have an auth token so that the connect will be successful.
    Untitled.txt
    a
    j
    • 3
    • 16
  • t

    Trey

    04/27/2022, 5:14 PM
    What would be the correct way to launch another coroutine based on the value returned from a flow?
    m
    a
    • 3
    • 6
  • t

    Tong Zhang

    04/28/2022, 3:09 AM
    Why comment this line15 ,also get the same output?
    e
    • 2
    • 2
  • j

    james

    04/28/2022, 5:05 AM
    Is anyone here familiar with the Open Telemetry Kotlin implementation: https://github.com/open-telemetry/opentelemetry-java/tree/main/extensions/kotlin. I'm trying to find the bit that allows the Span to propogate context across coroutines from a non-suspendable function:
    runBlocking {
            val error = IllegalAccessException("Bad things are happening!")
            val message = "Isn't it a nice day"
            Span.current()?.let { span ->
                val attributes = Attributes.builder().apply {
                    message?.let { put("error_message", it) }
                }
                    .build()
    
                span.setStatus(StatusCode.ERROR)
                span.recordException(throwable, attributes)
            }
            
            launch { 
                // This will cause the spans to get linked together and then sync metadata from the above. 
                @WithSpan
                suspendFunction()
            }
        }
    The reason i'm asking is that i'm trying to understand some strange behavior in our system where the context doesn't always propagate from a parent to child correctly.
    e
    o
    a
    • 4
    • 10
  • c

    Colton Idle

    04/28/2022, 3:57 PM
    I always have trouble seeing a "bug" in my code similar to this. It just doesn't make sense to me why if I'm collecting a flow that lasts forever, that my next coroutine will never get called.
    viewModelScope.launch {
      repository.getBooks().collect { list ->
        state.books.clear()
        state.books.addAll(list)
      }
    
      repository.doSomething() <--- Will never get called
    }
    I almost want to write a lint check or something to prevent myself from shooting myself in the foot. Anyone have any suggestions on how to change my mindset on this?
    j
    n
    +7
    • 10
    • 30
  • i

    ildar.i [Android]

    04/29/2022, 8:18 AM
    is there a way to do this properly?
    firstFlow.combine(secondFlow) { text: String, role: Role ->
                repository.getProcessList(role.apiParam, text)//returns new flow each time
            }.flatMapLatest {
                it
            }
    m
    j
    • 3
    • 4
  • t

    Tower Guidev2

    04/29/2022, 10:59 AM
    Hi i was watching a Udemy course on coroutine cooperative cancellation and they showed
    isActive
    as an approach to "join in with cancellation", however
    isActive
    is now showing as deprecated what can/should I use now?
    s
    • 2
    • 5
  • n

    Nowak

    04/29/2022, 1:34 PM
    Hi, I want to have something like Mutex (or like Sempahore with permits 1 action per certain key), but which is attached to certain value, for example entity id and don’t allow concurrent operations on the same entity. Id’ like to queue not all invocation but split them by some key (like entity id). Any ideas how to do that with Kotlin Coroutines 🙂 ?
    p
    t
    • 3
    • 4
  • a

    Aidan Low

    04/29/2022, 2:07 PM
    If I have some best-effort code, I might write it as
    try {
       foo()
    } catch (ex: Exception) {
       // ignore failures, best effort
    }
    but if I'm inside a coroutine, will this screw up cooperative cancellation? Do I need to do something like
    try {
      foo()
    } catch (ex: CancellationException) {
      throw ex
    } catch (ex: Exception) {
      // ignore failures, best effort
    }
    ?
    t
    e
    • 3
    • 8
Powered by Linen
Title
a

Aidan Low

04/29/2022, 2:07 PM
If I have some best-effort code, I might write it as
try {
   foo()
} catch (ex: Exception) {
   // ignore failures, best effort
}
but if I'm inside a coroutine, will this screw up cooperative cancellation? Do I need to do something like
try {
  foo()
} catch (ex: CancellationException) {
  throw ex
} catch (ex: Exception) {
  // ignore failures, best effort
}
?
t

Tijl

04/29/2022, 2:09 PM
yes, you do
a

Aidan Low

04/29/2022, 2:28 PM
I was afraid of that. Thanks. 🙂
e

ephemient

04/29/2022, 3:43 PM
that also screws up Java thread interruption
a

Aidan Low

04/29/2022, 5:15 PM
that also screws up Java thread interruption
Will that be handled by re-throwing CancellationException as in my second block of code?
Or are there additional changes required for the Java thread case?
e

ephemient

04/29/2022, 5:26 PM
Java uses a different InterruptedException
in general catching and failing to rethrow exceptions is a bad idea. only handle exceptions you know you can handle
a

Aidan Low

04/29/2022, 5:28 PM
Yeah, I'm not super happy about it either. (massive legacy codebase 🥳 )
View count: 28