https://kotlinlang.org logo
Docs
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
  • s

    Stefan Oltmann

    02/10/2022, 1:36 PM
    I'm a bit confused... since when does
    cancel()
    throw a
    JobCancellationException
    to the calling thread?
    kotlinx.coroutines.JobCancellationException: StandaloneCoroutine was cancelled; job="coroutine#2444":StandaloneCoroutine{Cancelling}@6b6879d8
    	at kotlinx.coroutines.JobSupport.cancel(JobSupport.kt:1605)
    	at kotlinx.coroutines.Job$DefaultImpls.cancel$default(Job.kt:189)
    ✅ 1
    j
    l
    • 3
    • 34
  • m

    Marcelo Hernandez

    02/10/2022, 9:36 PM
    Anyone know if it is safe for an app (Android app specifically) that is still on Coroutines
    1.5.2
    to use a 3rd party library that is built with Coroutines
    1.6.0
    . I see in the changelog that there are some breaking changes which is why I ask.
    l
    p
    • 3
    • 5
  • m

    Matthias Geisler

    02/10/2022, 10:08 PM
    Hey, I stumbled upon something strange -> when calling a Channel from a suspending lambda...the Channel get stucked...is this expected?:
    fun randomFunction() {
        val channel = Channel<String>()
        val lambda = suspend {
            channel.send("abc")
        }
    
        runBlocking(randomContext) {
            lambda()
    
            println(channel.receive())
        }
    }
    s
    • 2
    • 2
  • a

    Ahmad Dudayef

    02/12/2022, 1:46 AM
    Hi everyone, I try to implement StateFlow in viewmodel, but i confused how to add Loading state, i try to follow official documentation https://developer.android.com/kotlin/flow/stateflow-and-sharedflow, but i think it's just show state success and error, my question is how to add loading state using StateFlow in viewmodel ?
    n
    u
    • 3
    • 2
  • s

    Shreyas Patil

    02/12/2022, 8:34 AM
    I'm trying this with something like
    inline fun <T, R> Flow<T>.concurrentMap(
        concurrency: Int,
        @BuilderInference crossinline block: suspend (T) -> R
    ) = flow<R> {
        val scope = CoroutineScope(Executors.newFixedThreadPool(concurrency).asCoroutineDispatcher())
        val deferredResults = mutableListOf<Deferred<R>>()
        collect { value ->
            deferredResults.add(scope.async { block(value) })
        }
        deferredResults.awaitAll().forEach { newValue -> emit(newValue) }
        scope.cancel()
    }
    s
    • 2
    • 5
  • m

    martmists

    02/13/2022, 3:01 PM
    How would I use kotlinx.coroutines in combination with a blocking framework like lwjgl? I can't find anything in the docs about cases like this
    g
    l
    n
    • 4
    • 52
  • t

    Tristan

    02/13/2022, 11:37 PM
    Hello, I am trying to understand how works the frozen concept. I have the following piece of code:
    class UserRepository(
        private val userDataSource: UserDataSource,
        private val coroutineScope: CoroutineScope = CoroutineScope(Dispatchers.Default)
    ) {
        private val userMutex = Mutex()
        private var user: User? = null
    
        suspend fun fetch(userId: String): User? {
            println("Fetch user")
            println("context = " + coroutineContext) // prints Main
    
            if (user === null) {
                val result = withContext(coroutineScope.coroutineContext) {
                    println("Switch context")
                    println("context = " + kotlin.coroutines.coroutineContext) // prints Dispatched
                    adsSdkConfigurationDataSource.getUser(userId)
                }
    
                publisherConfigurationMutex.withLock {
                    println("Mutation")
                    println("context = " + coroutineContext) // prints Main
                    publisherConfigurationApiModel = result
                }
            }
    
            return publisherConfigurationMutex.withLock {
                publisherConfigurationApiModel
            }
        }
    }
    My logs look like
    Instantiate UserRepository
    context = [StandaloneCoroutine{Active}@2272df8, MainDispatcher]
    Is UserRepository frozen? false
    
    Fetch user
    context = [StandaloneCoroutine{Active}@2272df8, MainDispatcher]
    
    Switch context
    context = [DispatchedCoroutine{Active}@3921848, WorkerCoroutineDispatcherImpl@2225538]
    
    Mutation
    context = [StandaloneCoroutine{Active}@2272df8, MainDispatcher]
    Uncaught Kotlin exception: kotlin.native.concurrent.InvalidMutabilityException: mutation attempt of frozen com.me.UserRepository@227a228
    Why after coming back to the context that created the
    UserRepository
    I cannot perform a mutation?
    n
    j
    • 3
    • 4
  • c

    Can Korkmaz

    02/14/2022, 8:50 AM
    Hi, I was revising coroutines and dispatchers today and noticed in docs that setting dispatcher with newSingleThreadContext is a very expensive operation, but I don't understand why. Why would it be more expensive than dispatching it at any other thread, such as main or default, or io. Since coroutines aren't blocking, thread allocated with newSingleThreadContext can be used at any other part of the program. If its expensiveness caused by its job being executed by a single thread concurrently, wouldn't it be at most as expensive as posix pthreads?
    j
    • 2
    • 3
  • j

    juliocbcotta

    02/14/2022, 10:21 AM
    So, I am using coroutines 1.6 and in my data source I have this method
    override fun sumSelectedFees(): Single<Float> = rxSingle(workDispatcher) {
        dao.findDeliveryModeShippingOptions(true)
            .fold(0f) { total, shippingOption -> total + shippingOption.feeValue }
    }
    and I trying to call this in my test
    @Test
    fun `should sum all inserted fees for delivery`() = runTest {
        val dataSource = dataSource = DeliveryModesDataSourceImpl(dao, UnconfinedTestDispatcher())
        dataSource.sumSelectedFees()
            .test()
            .assertValue(0f)
    }
    but my test is failing since the test is not waiting the rx call
    .test()
    to complete.. I Used
    UnconfinedTestDispatcher
    here, but I am not sure what I dispatcher I should be using in this case.
    s
    d
    • 3
    • 24
  • k

    kschlesselmann

    02/14/2022, 11:36 AM
    Hi! I'm coming from Spring Webflux/Reactor and now I try to orchestrate a lot of asynchronous I/O with Flows. Currently it seems that my flows behave rather sequential. Could someone point out what the proper way to do something like
    Flux.just(…).flatMap { someAsnyStuff(it) }.subscribe()
    would be with a Flow? It seems that
    myFlow.flatMapMerge { someSuspendingStuff(it) }.collect()
    does not result in the same concurrency/throughput 😕
    j
    • 2
    • 4
  • s

    Sean Proctor

    02/14/2022, 2:17 PM
    I have a suspending function that returns a flow. It seems like it should be trivial to make it a function that returns immediately. I think
    flow { getSubscriptionFlow().collect { emit(it) } }
    would work, but it looks weird. Is there a simpler way to write that?
    j
    e
    g
    • 4
    • 16
  • l

    Lost Illusion

    02/14/2022, 9:51 PM
    I have a SharedFlow which outputs frames decoded from a socket. One of the steps I am required to do is send a handshake, and then I should get one back. I confirm that this is indeed getting passed to the flow and I can even retrieve it using the following piece of code
    incoming.filterIsInstance<WampRawTransportPacket.Handshake>().first()
    however, I also want to have a timeout around it as to not hang forever if the remote server does something weird. So I used the withTimeoutOrNull function, but I encounter some odd behavior.
    withTimeoutOrNull(connectionConfig.handshakeTimeout) {
        incoming.filterIsInstance<WampRawTransportPacket.Handshake>().first()
    } ?: throw WampTimeout(
        remoteAddress,
        "Timed out waiting ${connectionConfig.handshakeTimeout}ms for a handshake back!"
    )
    It will always time out after 5 seconds (that is what handshakeTimeout is currently configured at). If I take it out of the timeout, it works flawlessly and returns nearly instantly. Is there some side effect of the coroutine that timeout provides that I don't know about?
    • 1
    • 1
  • e

    expensivebelly

    02/15/2022, 8:25 AM
    How would you guys wrap a
    Callable
    in a coroutine?
    j
    s
    • 3
    • 9
  • k

    kschlesselmann

    02/15/2022, 2:23 PM
    https://kotlinlang.org/docs/flow.html#buffering – why does it take 1000ms to complete the buffered flow and not ~600ms? I thought `.buffer(
    and/or
    .flowOn`would result in parallelism so in my mind it'd take 300ms for
    simple
    to complete and then again 300 ms to process the last element of
    simple
    => ~600ms to complete everything.
    e
    j
    • 3
    • 5
  • a

    Anshulupadhyay03

    02/15/2022, 3:18 PM
    suspend fun flowsWithCombine() {
            val myFlow = flowOf("some value")
            val lettersFlow = flowOf("A", "D1", "C",  "E", "F", "G", "H").onEach { delay(500) }
            myFlow.map { value->
                val newValue = lettersFlow.first() 
                println("before $newValue")
                if(newValue == "D1") {
                    return@map "D1"
                }else {
                    delay(1000)
                    val newValue = lettersFlow.first() // here i still get A only though i expect newValue as D1
                     println("after $newValue")
                    if(newValue == "D1")  return@map "D1" else return@map value
                }
            }.collect {
                println(it) // This should print D1 
            }
        }
    s
    n
    • 3
    • 13
  • c

    Can Korkmaz

    02/16/2022, 4:29 PM
    LaunchedEffect(key1 = true) {        sharedViewModel.getAllTasks()    }
    val allTasks by sharedViewModel.allTasks.collectAsState()
    This is from Stevdza's course. How can he be sure that getAllTasks() will have completed (fetched all tasks from room) before the second line.
    j
    • 2
    • 2
  • m

    Mikhail Buzuverov

    02/17/2022, 4:22 AM
    Hello. Could you explain how exception in coroutines work? I have this demo code:
    import kotlinx.coroutines.*
    
    fun main() = runBlocking {
        val average = GlobalScope.calculateAverageAsync(emptyList())
    
        try {
            println(average.await())
        } catch (ex: ArithmeticException) {
            println("Calculation error")
        }
    }
    
    fun CoroutineScope.calculateAverageAsync(list: List<Int>): Deferred<Int> = async {
        list.sum() / list.size
    }
    And it prints (as expected):
    Calculation error
    
    Process finished with exit code 0
    But if I call
    calculateAverageAsync
    in
    runBlocking's scope
    :
    import kotlinx.coroutines.*
    
    fun main() = runBlocking {
        val average = this.calculateAverageAsync(emptyList())
    
        try {
            println(average.await())
        } catch (ex: ArithmeticException) {
            println("Calculation error")
        }
    }
    
    fun CoroutineScope.calculateAverageAsync(list: List<Int>): Deferred<Int> = async {
        list.sum() / list.size
    }
    I got another result:
    Calculation error
    Exception in thread "main" java.lang.ArithmeticException: / by zero
    	at MainKt$calculateAverageAsync$1.invokeSuspend(main.kt:14)
    	at kotlin.coroutines.jvm.internal.BaseContinuationImpl.resumeWith(ContinuationImpl.kt:33)
    	at kotlinx.coroutines.DispatchedTask.run(DispatchedTask.kt:106)
    	at kotlinx.coroutines.EventLoopImplBase.processNextEvent(EventLoop.common.kt:279)
    	at kotlinx.coroutines.BlockingCoroutine.joinBlocking(Builders.kt:85)
    	at kotlinx.coroutines.BuildersKt__BuildersKt.runBlocking(Builders.kt:59)
    	at kotlinx.coroutines.BuildersKt.runBlocking(Unknown Source)
    	at kotlinx.coroutines.BuildersKt__BuildersKt.runBlocking$default(Builders.kt:38)
    	at kotlinx.coroutines.BuildersKt.runBlocking$default(Unknown Source)
    	at MainKt.main(main.kt:3)
    	at MainKt.main(main.kt)
    
    Process finished with exit code 1
    As I can see the exception handler worked and printed "Calculation error". So exception was caught. But as different from previous case
    runBlocking
    was cancelled and main thread got the same
    ArithmeticException
    . I don't understand how to handle exception in case of structured concurrency. Nothing I tried works - exception cancels jobs and reaches
    runBlocking
    's outer code
    s
    • 2
    • 10
  • e

    Exerosis

    02/17/2022, 6:29 AM
    class Test<Value> {
        val listeners = ArrayList<suspend (Value) -> (Unit)>()
        val queue = ArrayDeque<() -> (Unit)>()
    
        suspend fun fire(value: Value) = suspendCoroutine<Unit> { continuation ->
            synchronized(queue) {
                if (queue.isEmpty()) {
                    for (listener in listeners)
                        listener(value)
                    continuation.resume(Unit)
                    while (queue.isNotEmpty())
                        queue.removeLast()()
                } else {
                    queue.add {
                        for (listener in listeners)
                            listener(value)
                        continuation.resume(Unit)
                    }
                    COROUTINE_SUSPENDED
                }
            }
        }
        fun listen(listener: suspend (Value) -> (Unit)) {
            listeners += listener
        }
    }
    If I have something along these lines, I know this isn't entirely valid... but the idea is that you fire an event and all the listeners should be fired with the given value before any of them are fired with a new value from elsewhere. Would it be possible to detect when a listener fires "recursively" for example:
    test.listen { if (it <= 0) test.fire(50) }
    And then instead of deadlocking, simply leave that listener "partially executed" and move to the next one until all of the listeners have had a chance to see the first value... then fire this recursively changed value out... then finish executing the partially executed listener... and finally if any other changes were pushed out concurrently elsewhere they would be fired. Ik this is a confusing question, but I figured the only way I could get close to this functionallity was by using continuatons.
    n
    • 2
    • 1
  • c

    charleskorn

    02/19/2022, 4:21 AM
    I’m using Kotlin/Native with the new memory model, and would like to launch a coroutine that does some blocking I/O. On the JVM, I’d use
    <http://Dispatchers.IO|Dispatchers.IO>
    for this, but that seems to only exist on the JVM. Is there something else I should use for Kotlin/Native?
    j
    d
    • 3
    • 2
  • r

    Ruben Quadros

    02/19/2022, 8:11 AM
    Do we need multiple coroutinescopes in an android app? If I provide a
    CoroutineScope
    as a dependency which every module can access then we can launch different coroutines using this one scope? Each child coroutine can then have its own
    CoroutineExceptionHandler
    as well. Is my understanding correct?
    s
    • 2
    • 8
  • j

    janvladimirmostert

    02/19/2022, 11:11 AM
    Is there a way in Coroutine Flows to say for example collect exactly 1 element, then collect 4 elements for example then collect more after that? flow.collect just drains the whole flow, flow.take(1) stops the flow, so this doesn't work:
    flow.take(1).collect {
       println(it)
    }
    flow.take(4).collect {
        println(it)
    }
    This is for parsing a byte flow that I'm reading from a socket, so in the case of take(4), it would be nice to do fold(4) that then spits out an Int Just not sure what options there are to only read a limited number of bytes and then let the next flow operation continue
    r
    a
    +2
    • 5
    • 9
  • a

    Abhi

    02/21/2022, 7:10 AM
    internal interface ExclusiveObject {
        val mutex: Mutex
    }
    
    internal suspend inline fun <R> ExclusiveObject.lockByCoroutineJob(block: () -> R): R {
        return if(mutex.holdsLock(coroutineContext.job)) block()
        else mutex.withLock(coroutineContext.job) {
            block()
        }
    }
    Is this safe? Each Co-routine checks if the mutex is held by itself, identified by the co-routine job, if yes, it executes the block, else, it executes the block, with lock. what are the pitfalls? Will this scale when the pressure is high on acquiring the mutex?
    a
    • 2
    • 2
  • j

    Jared Rieger

    02/21/2022, 11:53 AM
    Hey all, I wanted to investigate parallel map and filter functions in kotlin which lead me to this page. https://jivimberg.io/blog/2018/05/04/parallel-map-in-kotlin/ After implementing the pMap as described in the article, I found that the performance is far worse(37X slower) than the standard
    map
    function in kotlin. If I contrast this to Javas
    parallel
    stream, the java stream is far faster than the standard kotlin
    map
    function.
    suspend fun <I, O> Iterable<I>.pMap(f: suspend (I) -> O): List<O> = coroutineScope {
        map {
            async { f(it) }
        }.awaitAll()
    }
    val aP = (1..1000000).toList()
    
    @OptIn(ExperimentalTime::class)
    suspend fun main(args: Array<String>) {
    
        val timeP = measureTime {
            aP.parallelStream().map { it.plus(6) }
            aP.parallelStream().filter { it == 800000 }
        }
        println(timeP)
    
        val time = measureTime {
            aP.map { it.plus(6) }
            aP.filter { it == 800000 }
        }
        println(time)
    
    }
    What’s going on here? my expectation would have been that the
    pMap
    function to be on par with java’s
    parallelStream
    .
    t
    b
    • 3
    • 20
  • m

    mboudraa

    02/21/2022, 3:15 PM
    Hey folks, I'm trying to write a test to make sure coroutines are actually cancelled. But I keep failing at it. So I'm actually not sure I understand what I'm doing. Here's my use case: I have a
    Store
    which is essentially a wrapper on top of 2 flows. From this store I can dispatch events and those events will trigger coroutines to be executed on a given scope. However when I cancel the scope, the coroutines aren't cancelled...
    suspend fun dispatch(action: Action) {
            val currentState = stateFlow.value
    
            _actionFlow.tryEmit(action)
    
            supervisorScope {
                sideEffects.forEach { sideEffect ->
                    launch {
                        sideEffect(currentState, action)?.let { dispatch(it) }
                    }
                }
            }
    }
    Here's how my test is written
    @Test
        fun should_cancel_side_effect() = runTest {
            launch {
                val store = createStore(this) {
                    registerSideEffect sideEffect { _, action ->
                        if (action !is TestAction.Add) return@sideEffect null
                        delay(1_000)
                        return@sideEffect TestAction.Remove(3)
                    }
                }
    
                store.stateFlow.test {
                    CoroutineScope(Job()).launch childScope@{
                        store.dispatch(TestAction.Add(3))
                        cancel()
                    }.join()
    
                    assertEquals(TestCounterState(0), awaitItem())
    
                    this@launch.cancel()
                }
            }.join()
        }
    But the side effect returns the
    TestAction.Remove(3)
    like I never called
    cancel()
    on the scope that launched the coroutine
    n
    g
    • 3
    • 5
  • h

    harry.singh

    02/21/2022, 8:46 PM
    Hey all! Trying to understand how cancellation work with
    coroutineScope
    by launching a coroutine inside
    coroutineScope
    and then cancelling it. I was expecting the child coroutine to cancel but seems it continue to run even after being cancelled
    j
    • 2
    • 15
  • g

    Gabriel Melo

    02/22/2022, 5:26 PM
    Hello, everyone! Is there a way to apply the
    .map
    operator or something similar to a
    StateFlow
    and get another
    StateFlow
    back?
    s
    j
    • 3
    • 13
  • e

    eneim

    02/23/2022, 1:02 AM
    In this example https://github.com/Kotlin/kotlinx.coroutines/blob/master/kotlinx-coroutines-core/jvm/test/guide/example-exceptions-03.kt why do we need to call “yield” at line 19 and 23?
    n
    • 2
    • 1
  • k

    K Merle

    02/23/2022, 7:53 AM
    I would like to send network requests in queue. What would be a best way to achieve this with coroutines? Shall I set limit dispather to a single thread?
    s
    g
    • 3
    • 11
  • z

    zokipirlo

    02/23/2022, 9:52 AM
    Is there any difference between this two implementations? Which solution is preferred? 1.
    supervisorScope{
        list.map {
            async { doSomeApiCall(it) }
        }.awaitAll()
    }
    2.
    supervisorScope {
        list.map {
            async { doSomeApiCall(it) }
        }
    }.awaitAll()
    e
    j
    +3
    • 6
    • 15
  • g

    George

    02/24/2022, 2:23 PM
    Hi folks,
    override suspend fun acceptCode(code: String, account: SolidAccount): Unit = coroutineScope {
        val codeVerifierDeferred = async { sessionStorage.retrieveCodeVerifier(account) }
        val urlDeferred = async { sessionStorage.retrieveUserUrl(account) }
    
        authRequest(codeVerifierDeferred, urlDeferred, code, account)
    }
    override suspend fun acceptCode(code: String, account: SolidAccount): Unit = coroutineScope {
        val codeVerifierDeferred = async { sessionStorage.retrieveCodeVerifier(account) }
        val urlDeferred = async { sessionStorage.retrieveUserUrl(account) }
    
        authRequest(codeVerifierDeferred.await(), urlDeferred.await(), code, account)
    }
    Is there a real difference between these two? Thanks in advance !
    m
    • 2
    • 4
Powered by Linen
Title
g

George

02/24/2022, 2:23 PM
Hi folks,
override suspend fun acceptCode(code: String, account: SolidAccount): Unit = coroutineScope {
    val codeVerifierDeferred = async { sessionStorage.retrieveCodeVerifier(account) }
    val urlDeferred = async { sessionStorage.retrieveUserUrl(account) }

    authRequest(codeVerifierDeferred, urlDeferred, code, account)
}
override suspend fun acceptCode(code: String, account: SolidAccount): Unit = coroutineScope {
    val codeVerifierDeferred = async { sessionStorage.retrieveCodeVerifier(account) }
    val urlDeferred = async { sessionStorage.retrieveUserUrl(account) }

    authRequest(codeVerifierDeferred.await(), urlDeferred.await(), code, account)
}
Is there a real difference between these two? Thanks in advance !
m

Matthew Gast

02/24/2022, 2:41 PM
The first code block will immediately call
authRequest
, the second block will call authRequest after both
sessionStorage.retrieveCodeVerifier
and
sessionStorage.retrieveUserUrl
have completed execution. If you are familiar with Java,
Future
is an analogue to
Deferred
(noting that
Future.get
will block while
Deferred.async
suspends).
g

George

02/24/2022, 2:45 PM
Although im not familiar with Future of java i get what u mean. I pretty much get the differences but im curious about the performance. in my case inside my fun i have this
<http://webClient.post|webClient.post>().apply {
    val codeVerifier = codeVerifierDeferred.await()
    bodyValue(TokenRequestBody(code, codeVerifier).asUrlBody())
    val opUrl = urlDeferred.await()
    val dpopHeader = generateDPoPHeader(<http://HttpMethod.POST|HttpMethod.POST>, OpUrl(opUrl))
    header("DPoP", dpopHeader)
    header("content-type", "application/x-www-form-urlencoded")
    uri(opUrl.toTokenEndpoint()).exchangeToFlow {
        flowOf(it)
    }.collect {
My guess is that it would make a difference if was really awaiting much later in the fun?
m

Matthew Gast

02/24/2022, 2:51 PM
For this specific case, it does not look like it would matter much. However, there are definitely cases where you would want to pass the deferred reference instead of the completed value instead.
g

George

02/24/2022, 3:29 PM
Thanks for the pointers !
View count: 9