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

    Mukilesh Sethu

    08/09/2022, 6:09 AM
    I am looking for some help in debugging an issue. I am quite new to coroutines so please pardon my unfamiliarity. There is a long-running job (
    launch
    ) which polls data from a stream, and the reader is closed on
    job.invokeOnCompletion
    . We use
    suspendCancellableCoroutine
    to register a callback with the reader. 1 data point is polled at a time. We started seeing a potential memory leak with
    CancellableContinuationImpl/ChildContinuation
    created as part of
    suspendCancellableCoroutine
    . We expected only 1 active
    CancellableContinuationImpl/ChildContinuation
    per job and that is the case but job holds reference to old
    ChildContinuation
    from earlier which prevents it from getting GC'd (in the
    nodeList
    ) My understanding is that it is detached from the job on successful invocation of
    resume
    , which is what is expected from our service and even in the heap dump the
    state
    of `ChildContinuation`denotes it. I am wondering if there is any other scenario where
    CancellableContinuationImpl/ChildContinuation
    is not removed from the
    nodeList
    ? Or if there is a delay in removing it.
  • r

    rednifre

    08/09/2022, 1:53 PM
    Are these two basically identical? What’s the difference?
    fun suspendFoo(scope: CoroutineScope): Deferred<Int> =
            scope.async { 4 }
        
        suspend fun foo(): Int {
            delay(0)
            return 4
        }
    s
    r
    • 3
    • 13
  • k

    Kirill Grouchnikov

    08/09/2022, 3:23 PM
    Is it expected that the latest stable release of coroutines is still on Kotlin 1.6.21 instead of on 1.7.x?
  • s

    Sam

    08/10/2022, 12:51 PM
    By “thread safe” here they just mean that it won’t break when multiple threads use it at the same time.
    l
    s
    • 3
    • 4
  • r

    rocketraman

    08/10/2022, 7:24 PM
    1.6.4-native-mt was never released? https://search.maven.org/artifact/org.jetbrains.kotlinx/kotlinx-coroutines-bom
    e
    • 2
    • 4
  • n

    Nino

    08/11/2022, 1:46 PM
    Is there a better way to keep parallelism in the
    initializeStuffAndGetFoo()
    function between my coroutines without this dangerous
    first() as String
    ? https://pl.kotl.in/7fVqO3EXP
    import kotlinx.coroutines.*
    
    fun main() = runBlocking {
        println(initializeStuffAndGetFoo())
    }
    
    suspend fun initializeStuffAndGetFoo() = withContext(<http://Dispatchers.IO|Dispatchers.IO>) {
        listOf(
            async { getFooValue() },
            async { initA() },
            async { initB() },
        ).awaitAll().first() as String
    }
    
    suspend fun getFooValue(): String {
        delay(2_000)
        return "Foo"
    }
    
    suspend fun initA() = delay(1_000)
    suspend fun initB() = delay(3_000)
    j
    • 2
    • 6
  • l

    Lukas Lechner

    08/12/2022, 10:00 AM
    Is it possible to start a Coroutine in a flow operator, so that when the flow completes, the Coroutine is cancelled as well? I somehow need access to the scope of the flow, right?
    s
    j
    n
    • 4
    • 6
  • o

    oday

    08/15/2022, 6:47 PM
    so I have this piece of code:
    if (marketingConsentTypes != null && marketingConsentTypes.all { it in validEnumValues }) {
        viewModelScope.launch(coroutineDispatchers.main) {
            marketingConsentTypes.forEach { consentType ->
                giveConsent.execute(
                    GiveConsent.Input(
                        consentType = GiveConsent.ConsentType.valueOf(consentType),
                        hasGivenConsent = true
                    )
                ).await()
            }
    
            isLoading.postValue(false)
        }
    } else {
        error.postValue(Event(Throwable()))
    }
    the issue is not that I am running this usecase in a loop, that’s what I want the issue is that I would like to get back the Throwable that this usecase already does return for me, with Rx usually I’d get it back in the error block of the subscribe, here where can I get it to let my mutable property know that the error happened?
    s
    • 2
    • 5
  • f

    fitermay

    08/15/2022, 9:45 PM
    Is there a way to ensure consistency between flows? I want to ensure that several related flows’ values are consistent in terms of events they processed
  • f

    fitermay

    08/15/2022, 9:49 PM
    If say the value shared flowA and FlowB directly or indirectly depend on emitted value of flowC, I want to ensure I observe the value of those flows when both processed the latest value of flowC
  • f

    fitermay

    08/15/2022, 9:50 PM
    But I don't want to observe the values when one flow processed the latest value but the other hasn't
    f
    e
    t
    • 4
    • 21
  • d

    dimsuz

    08/16/2022, 11:05 AM
    If I have a
    Flow<Int>
    , say 1, 20, 30, 35, how could I produce a flow which "samples" this flow and counts the difference between last elements emitted in chunked time windows? for example sampleTime=20ms if
    1,20, 30
    got emitted in 20ms since start and then only one item
    35
    got emitted in next 20 ms, I would get
    29,5
    (
    30-1,35-30
    ) out. Should I combine sample with map with timestamps? Would be grateful for direction. Or should I write a fully custom "transform" function instead of trying to combine existing ones?
    b
    • 2
    • 2
  • c

    Curtis Ullerich

    08/16/2022, 5:08 PM
    what is an idiomatic way to issue a list of io-blocking calls and do something with each result as soon as it completes?
    f
    m
    • 3
    • 26
  • z

    Zoltan Demant

    08/17/2022, 6:30 AM
    When a component is destroyed, its CoroutineScope is cancelled. Id like to do one last thing at that point, do I do
    GlobalScope.launch {}
    or `scope.launch(context = NonCancellable) {}`; or are they basically the same thing? My operation is just a few millis long.
    s
    n
    a
    • 4
    • 9
  • c

    Christopher Porto

    08/18/2022, 7:37 AM
    Hello, I was wondering if its possible to ensure continuation is ran on same thread from call site, for e.g
    suspend fun test() {
        val response = bar()
        println("I want this to be on same thread as it was before doing bar call")
    }
    
    suspend fun bar() {
        val response = someOtherCallThatSwitchesThread()
        return response
    }
    I figured calling
    suspendCoroutine
    inside bar then launching new coroutine that resumes the continuation with the response would work and while it does change the thread, it doesnt go back to original.
    s
    n
    • 3
    • 12
  • z

    Zoltan Demant

    08/18/2022, 7:54 AM
    Whats the recommended approach for using
    scope.launch {}
    from MainScope? Generally, the task itself will run with the "correct" dispatcher, for example: loading something from a database is always executed using
    withContext(<http://Dispatchers.IO|Dispatchers.IO>)
    . But to me it seems that I might as well specify something like
    Dispatchers.Default
    in the launch block, so that all tasks are at least off-loaded from the main thread by default? As a real life scenario, I was just working on an issue where UI froze after the user had selected a file to import from; I had failed to realize that contentResolver.openInputStream(uri) was blocking rather than reading from the inputStream itself. If I had been using
    Dispatchers.Default
    , this wouldnt have been a problem. Now, instead I have to wrap each individual call like this (there arent many, but still) in a
    withContext(Dispatchers.Default/IO)
    .
    r
    t
    • 3
    • 8
  • d

    ddimitrov

    08/18/2022, 11:00 AM
    Hello, can anybody point me to a guide for debugging hanging coroutines setup? I looked at a thread dump, but it only shows a bunch of parked coroutines. I would like to get a graph of suspended continuations or something.
    l
    • 2
    • 1
  • i

    itnoles

    08/19/2022, 1:43 AM
    check that delay imports
    r
    • 2
    • 1
  • r

    rrva

    08/19/2022, 10:07 AM
    How can this be rewritten in a better way wrt structured concurrency and flow etc
    fun <A, B> Iterable<A>.parallelMap(context: CoroutineContext, f: suspend (A) -> B): List<B> = runBlocking {
        map { async(context) { f(it) } }.map { it.await() }
    }
    
    @OptIn(ExperimentalCoroutinesApi::class)
    private val apiPool = Dispatchers.IO.limitedParallelism(10)
    
    val results = foo.parallelMap(apiPool) { fetchStuffFromRestAPI(it.id) }
    s
    • 2
    • 5
  • v

    Vsevolod Kaganovych

    08/19/2022, 2:49 PM
    Who can help me with next: how can I test the emitted value from
    MutableSharedFlow
    which uses debounce? Example: I’m using this flow to track the input text in textfield, debounce and distinct it, and if it passes I make some calculations. But if in unit test I emit the value, it never enters the
    collectLatest {}
    lambda.
    m
    • 2
    • 3
  • w

    wrongwrong

    08/20/2022, 6:11 AM
    Is the
    future
    function in
    kotlinx-coroutines-jdk8
    available as per the sample code? https://kotlinlang.org/api/kotlinx.coroutines/kotlinx-coroutines-jdk8/#:~:text=to%20the%20future-,Example,-Given%20the%20following The definition shows that a
    CoroutineScope
    is required, and actually reproducing the sample code results in a compile error. https://kotlinlang.org/api/kotlinx.coroutines/kotlinx-coroutines-jdk8/kotlinx.coroutines.future/future.html Also, if there is a way to achieve the same behavior as in the sample code, I would appreciate it if you could let me know.
    • 1
    • 1
  • z

    Zoltan Demant

    08/20/2022, 6:13 AM
    I want to cancel all the pending work thats being done in my
    CoroutineScope
    , but I need to do it inside a suspending block of my scope. This feels like a really bad idea, is there a better approach?
    scope.launch {
        // Do some suspending work
        scope.coroutineContext.cancelChildren()
        // Ordering becomes very important - any code from here and on is never executed.
        // This isnt a problem by itself as I dont have any more code here, but it has introduced very subtle
        // bugs in the past
    }
    • 1
    • 1
  • j

    Joe Altidore

    08/20/2022, 10:23 PM
    I am attempting to perform parallel API calls with kotlin. However, the second api call is cancelled when the first call's await() method is called. How do i force all methods to finish executing before returning from the method. The code snippet
    suspend fun isFinished(token: String): Boolean {
        return coroutineScope {
            val a = async {
                updateProfile(token = token)
            }
            val b = async{
                updateStatus(token = token)
            }
            (a.await()) && (b.await())
        }
    }
    Methods updateProfile(token: String) and updateStatus(token: String) are the api methods
    j
    u
    l
    • 4
    • 30
  • l

    Lukas Lechner

    08/21/2022, 8:22 AM
    Are there any use cases for using Channels in Android Development, or are you exclusively using Flows in your apps?
    l
    • 2
    • 8
  • d

    dan.the.man

    08/21/2022, 9:38 PM
    Is there any known weirdness with the latest stable versions of kotlin/coroutines and Mockito? I'm having an issue where my tests are provided mocks, the debugger confirms it's a mock, but the code actually tries to execute in those mocks
    j
    • 2
    • 3
  • r

    rishabhsinghbisht

    08/22/2022, 5:25 AM
    After upgrading to 1.6.21 from 1.5.21 we are getting fatal reports of
    kotlinx.coroutines.JobCancellationException
    ,
    kotlinx.coroutines.TimeoutCancellationException
    in firebase crashlytics. We are not able to reproduce this ourself. Any help appreciated?
    t
    • 2
    • 9
  • a

    Amir hossein Abdolmotallebi

    08/22/2022, 9:10 AM
    I faced with a problem when using runBlocking and flow::stateIn https://stackoverflow.com/questions/73442324/problem-with-kotlin-coroutine-runblocking-and-statein
    s
    • 2
    • 3
  • s

    Sergio C.

    08/22/2022, 1:56 PM
    Hi everyone! Is there a way to reuse the continuation in
    suspendCoroutine
    block?
    suspendCoroutine { continuation -> }
    I need to call continuation more than once but its throwing error
    java.lang.IllegalStateException: Already resumed
            at kotlin.coroutines.SafeContinuation.resumeWith(SafeContinuationJvm.kt:44)
    Any way to bypass this?
    c
    • 2
    • 2
  • l

    Lukas Lechner

    08/23/2022, 8:54 AM
    How can I print out the coroutine context in which a flow operator is running?
    s
    • 2
    • 4
  • l

    Lilly

    08/23/2022, 8:48 PM
    I'm using flow
    combine
    the first time trying to combine multiple flows to an single object. One of the flows return items which are part of a
    List
    . How can I get access to the previous combined object to accumulate the items of the list?
    e
    • 2
    • 5
Powered by Linen
Title
l

Lilly

08/23/2022, 8:48 PM
I'm using flow
combine
the first time trying to combine multiple flows to an single object. One of the flows return items which are part of a
List
. How can I get access to the previous combined object to accumulate the items of the list?
e

ephemient

08/23/2022, 9:08 PM
one option is to wrap the flows with something like
fun <T, R> Flow<T>.withHistory(
    maxSize: Int,
    transform: suspend (List<T>) -> R,
): Flow<R> {
    require(maxSize > 0)
    return flow {
        val window = ArrayDeque<T>(maxSize)
        collect {
            if (window.size == maxSize) window.removeFirst()
            window.addLast(it)
            emit(window.toList())
        }
    }
}
if you only need one previous item,
fun <T, R> Flow<T>.zipWithPrevious(
    transform: suspend (T?, T) -> R,
): Flow<R> = flow {
    var prev: T? = null
    collect { cur ->
        emit(transform(prev, cur))
        prev = cur
    }
}
l

Lilly

08/24/2022, 5:56 PM
Thanks @ephemient Another related question about `combine`: I use it to combine 4 Flows, 2 Flows come from
BroadcastReceivers
so they do not
emit
that frequently. In my logs, I can see that one of the Flows emit but the
transform
block of combine is not triggered. Does combine has some hidden behavior?
fun startListening() {
        combine(
            bluetoothLocal.discoverDevices(),
            bluetoothLocal.discoveryState(), // emits a value but transform block is not triggered
            bluetoothLocal.bluetoothAdapterState(),
            protocolState,
        ) { discoveredDevice, isScanning, isBluetoothEnabled, protocolState ->
            ....
       }.launchIn(scope)
     }
I would expect that transform block is called everytime one of the flows emit a value, isnt that the case?
ok I got it. combine expects initial values for every flow before transform is triggered.
bluetoothLocal.bluetoothAdapterState()
does not has an initial value. When I emit an initial value like
bluetoothLocal.bluetoothAdapterState().onStart { emit(bluetoothLocal.isEnabled) }
it works like expected.
View count: 7