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

    Robert Jaros

    03/09/2023, 2:35 PM
    https://github.com/Kotlin/kotlinx.coroutines/releases/tag/1.7.0-Beta
    l
    • 2
    • 1
  • t

    Tower Guidev2

    03/09/2023, 4:32 PM
    I thought I understood kotlin coroutines 🤦‍♂️
    s
    p
    r
    • 4
    • 18
  • v

    Vsevolod Tolstopyatov [JB]

    03/09/2023, 4:50 PM
    📣 📣 📣 kotlinx.coroutines 1.7.0-Beta is here! This is a Beta of the major release that contains multiple significant reworks and improvements: • Much more efficient new
    Channel
    ,
    Mutex
    and
    select
    implementations • JPMS support • Merge of
    kotlinx-coroutines-core
    and
    kotlinx-coroutines-jdk8
    • Partial stabilization and notable improvements of
    kotlinx-coroutines-test
    • More K/N support: all official targets, better dispatchers,
    <http://Dispatchers.IO|Dispatchers.IO>
    And many more! Full changelog: https://github.com/Kotlin/kotlinx.coroutines/releases/tag/1.7.0-Beta
    c
    r
    • 3
    • 2
  • d

    Daniel

    03/10/2023, 6:12 PM
    Hello all, I am new at kotlin, Is this the correct way that the flow is executed?
    suspend fun Logout(token: String) {
        val userId = appService.currentUser!!.id       ///// this will execute 1st
        realm.write {                                  ///// this will execute 2nd
            var user = query<UserInfo>("_id = $0", userId).first().find()
            if (user != null) {
                user = findLatest(user)!!.also {
                    it.FCMToken.remove(token)
                }
                copyToRealm(user)
            }
        }
        withContext(Dispatchers.Default) {             ///// this will execute 3rd
    
            realm.syncSession.uploadAllLocalChanges()  ///// this will execute 4rd
    
            appService.currentUser?.logOut()           ///// this will execute 5th
        }
    }
    Are they executed in a linear way?
    s
    u
    e
    • 4
    • 4
  • k

    Kshitij Patil

    03/14/2023, 5:16 AM
    I’m trying to implement concurrent system using actor models. Not able to wrap my head around sending delayed message to actor. Attaching my snippet to implement the same. Is this correct?
    ActorDelayedMessage.kt
    u
    • 2
    • 9
  • s

    Slackbot

    03/14/2023, 11:19 AM
    This message was deleted.
    u
    d
    • 3
    • 23
  • n

    natario1

    03/14/2023, 12:16 PM
    I’m struggling to redesign this thing:
    class Processor {
        private val condition1 = MutableStateFlow(false)
        private val condition2 = MutableStateFlow(false)
        private suspend fun process(): Processed { ... }
        init {
            someScope.launch {
                combine(condition1, condition2) { a, b -> a || b }
                    .collectLatest { process() }
            }
        }
        fun setCondition1() { condition1.value = true }
        fun setCondition2() { condition2.value = true }
    }
    When the user changes one of the conditions, I would like to • know if this change did not trigger a
    process()
    (for example, throw if not) • return something like a
    Deferred<Processed>
    to be (optionally) awaited. Does anyone have any idea on how to achieve this?
    d
    • 2
    • 1
  • j

    jean

    03/14/2023, 12:52 PM
    I have the following code and I want to make sure the callback is unregistered. How can I trigger
    awaitClose
    from my unit test ? I tried to cancel
    testScope
    but that triggers a
    ClosedReceiveChannelException: Channel was closed
    since turbine gets also canceled.
    private fun someApiCallbackToFlow(api: API) = callbackFlow {
        val callback = object : ApiCallback {
            override fun next(data: Int) {
                trySend("Success")
            }
        }
        api.register(callback)
        awaitClose {
            println("callback unregistered")
            api.unregister(callback)
        }
    }
    
    
    @OptIn(ExperimentalTime::class)
    @Test
    fun test() = testScope.runTest {
        val api = SomeApi()
        val flow = someApiCallbackToFlow(api)
        flow.test {
            assertEquals(1, api.callbacks.size)
            api.getData()
            assertEquals("Success", awaitItem())
            // how can I check there isn't any callback here?
        }
    }
    p
    • 2
    • 6
  • k

    KotlinLeaner

    03/15/2023, 10:40 PM
    Hi guys, I am getting strange issue using
    runTest
    . I have a simple viewModel
    class LoadingViewModel(
        private val ioDispatcher: CoroutineDispatcher,
    ) : ViewModel() {
    
        var xyz by mutableStateOf(false)
        fun checkXyz() {
            viewModelScope.launch {
                delay(1000L)
                xyz = true
            }
        }
    }
    more code in 🧵
    j
    e
    • 3
    • 11
  • p

    Patrick Steiger

    03/16/2023, 12:15 AM
    Wondering what would be the idiomatic way to launch multiple coroutines in a
    supervisorScope
    while still capturing all exceptions (aggregated) that are thrown in them. Note that I do not want failure of a child to cancel other children (or the scope), hence supervisor scope, but I might want to “sum” (probably
    addSuppressed
    ) all exceptions and throw it later after scope is done Right now I’m using
    withContext
    with a custom
    CoroutineExceptionHandler
    that puts all exceptions in a collection and later reduce the collection and throw, but it just feels boilerplate-y and wonder if I’m missing something
    s
    k
    • 3
    • 3
  • s

    Sam Stone

    03/16/2023, 8:05 PM
    Am I wrong in assuming that there haven’t been many books on coroutines yet because some of the APIs have been experimental (e.g. @FlowPreview and @ExperimentalCoroutinesApi)? If correct, when will they be stable?
    p
    g
    • 3
    • 2
  • p

    PHondogo

    03/17/2023, 9:27 PM
    Hello! When updated to version 1.7.0-Beta got error on mergeDebugJavaResource while building Android apk. (2 files found with path 'META-INF/versions/9/previous-compilation-data.bin') There reason is that in both kotlinx-coroutines-android-1.7.0-Beta.jar and kotlinx-coroutines-core-jvm-1.7.0-Beta.jar there is existence of META-INF/versions/9/previous-compilation-data.bin. While at 1.6.4 version this file exists only in kotlinx-coroutines-core-jvm. kotlinx-coroutines-android depends on kotlinx-coroutines-core-jvm, so when add dependency to kotlinx-coroutines-android also got kotlinx-coroutines-core-jvm as transitive dependency. Is it a bug or there should be changes from library user's side?
    j
    • 2
    • 7
  • t

    Teimatini Marin

    03/18/2023, 12:21 AM
    Hi all! Pipeline channels is a commun pattern for concurrency... I'm trying to move some code from Channels to Flows... but not sure what's the best way to pipeline Flows without causing callback-hell issue as below:
    import kotlinx.coroutines.*
    import kotlinx.coroutines.flow.Flow
    import kotlinx.coroutines.flow.flow
    
    fun main() = runBlocking {
        produceFlowNumbers()
            .collect { // First collect
                squareFlow(it)
                    .collect { // Second collect inside First collect
                        println(it)
                    }
            }
        println("Done!") // we are done
    }
    
    fun produceFlowNumbers() : Flow<Int> = flow {
        var x = 1
        while (x < 5) emit(x++) // infinite stream of integers starting from 1
    }
    
    fun squareFlow(number: Int): Flow<Int> = flow {
        emit(number*number)
    }
    I have the feeling that I'm missing something here. Any suggestion experts?
    e
    j
    • 3
    • 5
  • n

    Nino

    03/20/2023, 3:35 PM
    Hey ! I want to ask people around if
    runCatching
    is in use in any of your Kotlin (or Android) projects ? I feel my team is abusing it and I'm trying to understand if there's any "pros" about using it in any coroutine-based codebase. My team just adopted this convention and I'm at loss of words. (Examples in thread for anyone interested)
    j
    s
    +5
    • 8
    • 107
  • m

    Mark Vogel

    03/20/2023, 5:33 PM
    I'm attempting to create a small wrapper for SharedFlows to add some priority functionality and some better dependency injection usability. While doing this I'm observing some extremely odd behavior that I can't seem to figure out. Using this test class which mirrors my unit tests as much as possible you can see the behavior. Basically, I'm acquiring a lock to wait on the flow to be called in order to test the outcome, but the lock is never released because the subscriber is never called despite having clearly subscribed. The extreme weirdness comes in when I add certain specific
    println
    calls that reference variables in which case the problem disappears while that statement is present. The pasted test class will print the following when ran (and never complete):
    Registering
    Registered
    Emitting
    Emitting here
    Subscribers
    0
    Done
    Suspending
    Note that is says there are zero subscribers and finished emitting even though it was registered. However, when uncommenting lines 59 or 63, it still says there are zero subscribers, but the object is emitted to my registered collector and the program finishes. I am relatively new to Flows and have avoided them mostly because of these kinds of things, but I would love to make them work since they are exactly what I need. I feel like I must be doing something wrong. I appreciate any help!
    d
    • 2
    • 8
  • l

    loloof64

    03/21/2023, 9:11 PM
    Hi ! I'm having an issue with coroutine in a Jetpack Compose for Desktop project. More in the thread 🧵 .
    s
    • 2
    • 19
  • l

    Luke

    03/22/2023, 2:44 PM
    In a suspend function, is there a way to check if the calling coroutine is cancelled?
    delay
    is accessible and does check the cancellation status so there must be a way right?
    s
    d
    e
    • 4
    • 4
  • d

    Daniel

    03/23/2023, 6:09 PM
    Hello, can someone help me with this please? https://stackoverflow.com/questions/75779125/kotlin-compose-how-to-know-when-suspend-function-is-finished?noredirect=1#comment133681725_75779125
  • d

    Daniel

    03/23/2023, 6:18 PM
    I would pay to someone that helps me refactor my login/logout methods
  • m

    martypitt

    03/24/2023, 8:43 AM
    I'm trying to upgrade to Coroutines
    1.7.0-Beta
    , and it appears that
    kotlinx.coroutines.future.future
    has been moved - does anyone know what it's replacement is?
    d
    • 2
    • 8
  • j

    Johann Pardanaud

    03/24/2023, 10:31 AM
    What is the recommended way to use MDCCOntext? For example, in a Ktor route like:
    routing {
        get("/some-route") {
            MDC.put("foo", "bar") // Will it leak in successive requests for the same route?
            println(MDC.getCopyOfContextMap())
            delay(1)
            println(MDC.getCopyOfContextMap()) // Should I use `withContext(MDCContext()) {}` here?
        }
    }
    Should I do something like this?
    routing {
        get("/some-route") {
            // Use MDCContext before modifying the MDC to ensure the data is restored
            withContext(MDCContext()) {
                MDC.put("foo", "bar")
                println(MDC.getCopyOfContextMap())
    
                // Use MDCContext before suspending the coroutine to ensure
                // the data is still available when resuming
                withContext(MDCContext()) {
                    delay(1)
                    println(MDC.getCopyOfContextMap())
                }
            }
        }
    }
    As you can see, I’m a bit lost and I’m not sure when I need to use
    MDCContext
    😬
  • j

    Jaro

    03/24/2023, 3:54 PM
    Hi all, I'm trying to replicate some
    CompletableFuture
    code in Java to
    Coroutines
    in Kotlin, the interface that my Kotlin class implements has functions that are returning
    CompletableFuture
    Here is example of functions that I want to rewrite
    private final Map<String, FooWrapper> fooRequests = new ConcurrentHashMap<>();
    
    public CompletableFuture<FooResponse> retrieveFoo(FooRequest request) {
        return completedFuture(...)
            .thenAccept(client::callFoo)
            .thenCompose(ignore -> storeFooRequest(request))
            .whenComplete((response, error) -> log(request, error));
    }
    
    private CompletableFuture<FooResponse> storeFooRequest(FooRequest request) {
        var fooWrapper = new FooWrapper(request, new CompletableFuture<>());
        fooRequests.put(request.getId(), fooWrapper);
        return fooWrapper.getResponseFuture();
    }
    eventually there will be call to other functions that will call
    complete
    on a
    CompletableFuture
    stored in
    fooRequests
    and allowing completion of
    retrieveFoo
    here is my Kotlin code
    private val fooRequests: ConcurrentHashMap<String, CompletableDeferred<FooResponse>> = ConcurrentHashMap()
    
    override fun retrieveFoo(request: FooRequest): CompletableFuture<FooResponse> {
        return GlobalScope.future {
            retrieveQuoteAsync(request)
        }
    }
    
    private suspend fun retrieveFooAsync(request: FooRequest): Deferred<FooResponse> {
        return coroutineScope {
            storeFooRequest(request)//.await()
        }
    }
    
    private suspend fun storeFooRequest(request: FooRequest): Deferred<FooResponse> {
        val deferred: CompletableDeferred<FooResponse> = CompletableDeferred()
        fooRequests[request.id] = deferred
        return deferred
    }
    I'm trying to replace
    CompletableFuture
    with
    CompletableDeferred
    but I do not know how to get the value without calling
    await()
    , I do not want it to block Any suggestion how to make it work in similar way to Java?
    j
    • 2
    • 9
  • s

    Seth Madison

    03/24/2023, 9:41 PM
    I think I am misunderstanding the semantics of
    transform
    . I have a flow along the lines of`sharedFlow -> transformWhile -> map` , and I see the
    map
    run even when the downstream collector has completed. Is this expected? Example in the thread.
    e
    • 2
    • 21
  • i

    Ismaïl

    03/25/2023, 1:08 PM
    Hey guys, I have a question that I just posted on Stackoverflow It’s about the coroutine scopes and structured concurrency Could someone please answer it
    p
    • 2
    • 7
  • i

    Ismaïl

    03/25/2023, 4:06 PM
    Here is simpler one 😄
  • a

    Arjan van Wieringen

    03/26/2023, 6:59 AM
    Am I correct that ‘coroutineScope’ function is the suspending equivalent of runBlocking? If so, wouldn’t it make more sense to have called it runSuspending?
    s
    j
    • 3
    • 11
  • i

    Ismaïl

    03/26/2023, 5:27 PM
    Hey guys I’m trying to understand how
    suspendCoroutine
    works, I tried to implement an example, here is the GitHub Gist link Does this code make sense ? it works but I was wondering if it can be improved somehow Thanks in advance
    f
    • 2
    • 3
  • j

    jean

    03/27/2023, 6:44 AM
    I have the following test, which fails. It seems like the update done by one flow does not affect the other one. Is this a case where I should use a
    Channel
    to be able to communicate data between coroutines?
    Untitled
    r
    n
    • 3
    • 2
  • s

    sanggggg

    03/28/2023, 3:18 AM
    Is it possible to create a test that terminates when all the fire & forgot coroutines in the test have completed? 🧵
    Untitled.kt
    j
    j
    • 3
    • 9
  • y

    Youssef Shoaib [MOD]

    03/28/2023, 3:57 PM
    I have a
    Thread
    that's already running (for legacy reasons, it needs to be a
    Thread
    for now). Inside a
    suspend
    function, how can I call
    thread.join()
    in a "better" manner? As in, so that the coroutine suspends until the thread finishes.
    c
    m
    s
    • 4
    • 11
Powered by Linen
Title
y

Youssef Shoaib [MOD]

03/28/2023, 3:57 PM
I have a
Thread
that's already running (for legacy reasons, it needs to be a
Thread
for now). Inside a
suspend
function, how can I call
thread.join()
in a "better" manner? As in, so that the coroutine suspends until the thread finishes.
c

CLOVIS

03/28/2023, 4:08 PM
withContext(<http://Dispatchers.IO|Dispatchers.IO>) { 
    thread.join() 
}
m

mkrussel

03/28/2023, 4:13 PM
There wouldn't be anything built in that is not blocking. Best option would be to add something at the end of the work the thread is doing that would notify listeners when it is done. You can then suspend and wait for the notification. This relies on you having some control over the thread and the work it is doing.
y

Youssef Shoaib [MOD]

03/28/2023, 4:15 PM
Looking at `Thread.join`'s code, it seems to just wait until
thread.isAlive
is false, so wouldn't I be able to use that as a condition to wait for? I do have control over the thread code, but I'm trying to not be too invasive
I came up with this, but I don't know if its better or not:
coroutineScope { launch { while (thread.isAlive) delay(10) } }
s

simon.vergauwen

03/28/2023, 4:17 PM
runInterruptible is probably a better choice than
withContext
. A non-blocking option would be to somehow pass a
CompletableDeferred
as the task running in the
Thread
and await that. I would personally prefer
join
in favor of looping, you can potentially also use newSingleThreadContext instead of
<http://Dispatchers.IO|Dispatchers.IO>
but be sure to close it.
c

CLOVIS

03/28/2023, 4:19 PM
Oh, indeed
runInterruptible(<http://Dispatchers.IO|Dispatchers.IO>)
looks more appropriate. It's still blocking a thread.
y

Youssef Shoaib [MOD]

03/28/2023, 4:23 PM
Thanks Ivan and Simon. I ended up using a
CompletableDeferred
and completing it at the end of the thread's code, then awaiting it instead of calling
join
c

CLOVIS

03/28/2023, 4:24 PM
That's even better 👍
s

simon.vergauwen

03/28/2023, 4:25 PM
That would indeed the best option if possible, be sure to add it in a
try { } finally { }
block so it gets called regardless of exceptions 😉
y

Youssef Shoaib [MOD]

03/28/2023, 4:28 PM
@simon.vergauwen Ooops yes I forgot! Good catch
c

CLOVIS

03/28/2023, 4:30 PM
Pun intended? 🤔
View count: 1