https://kotlinlang.org logo
Join the conversationJoin Slack
Channels
100daysofcode
100daysofkotlin
100daysofkotlin-2021
advent-of-code
aem
ai
alexa
algeria
algolialibraries
amsterdam
android
android-architecture
android-databinding
android-studio
androidgithubprojects
androidthings
androidx
androidx-xprocessing
anime
anko
announcements
apollo-kotlin
appintro
arabic
argentina
arkenv
arksemdevteam
armenia
arrow
arrow-contributors
arrow-meta
ass
atlanta
atm17
atrium
austin
australia
austria
awesome-kotlin
ballast
bangladesh
barcelona
bayarea
bazel
beepiz-libraries
belgium
berlin
big-data
books
boston
brazil
brikk
budapest
build
build-tools
bulgaria
bydgoszcz
cambodia
canada
carrat
carrat-dev
carrat-feed
chicago
chile
china
chucker
cincinnati-user-group
cli
clikt
cloudfoundry
cn
cobalt
code-coverage
codeforces
codemash-precompiler
codereview
codingame
codingconventions
coimbatore
collaborations
colombia
colorado
communities
competitive-programming
competitivecoding
compiler
compose
compose-android
compose-desktop
compose-hiring
compose-ios
compose-mp
compose-ui-showcase
compose-wear
compose-web
connect-audit-events
corda
cork
coroutines
couchbase
coursera
croatia
cryptography
cscenter-course-2016
cucumber-bdd
cyprus
czech
dagger
data2viz
databinding
datascience
dckotlin
debugging
decompose
decouple
denmark
deprecated
detekt
detekt-hint
dev-core
dfw
docs-revamped
dokka
domain-driven-design
doodle
dsl
dublin
dutch
eap
eclipse
ecuador
edinburgh
education
effective-kotlin
effectivekotlin
emacs
embedded-kotlin
estatik
event21-community-content
events
exposed
failgood
fb-internal-demo
feed
firebase
flow
fluid-libraries
forkhandles
forum
fosdem
fp-in-kotlin
framework-elide
freenode
french
fritz2
fuchsia
functional
funktionale
gamedev
ge-kotlin
general-advice
georgia
geospatial
german-lang
getting-started
github-workflows-kt
glance
godot-kotlin
google-io
gradle
graphic
graphkool
graphql
graphql-kotlin
graviton-browser
greece
grpc
gsoc
gui
hackathons
hacktoberfest
hamburg
hamkrest
helios
helsinki
hexagon
hibernate
hikari-cp
hire-me
hiring
hongkong
hoplite
http4k
hungary
hyderabad
image-processing
india
indonesia
inkremental
intellij
intellij-plugins
intellij-tricks
internships
introduce-yourself
io
ios
iran
israel
istanbulcoders
italian
jackson-kotlin
jadx
japanese
jasync-sql
java-to-kotlin-refactoring
javadevelopers
javafx
javalin
javascript
jdbi
jhipster-kotlin
jobsworldwide
jpa
jshdq
juul-libraries
jvm-ir-backend-feedback
jxadapter
k2-early-adopters
kaal
kafka
kakao
kalasim
kapt
karachi
karg
karlsruhe
kash_shell
kaskade
kbuild
kdbc
kgen-doc-tools
kgraphql
kinta
klaxon
klock
kloudformation
kmdc
kmm-español
kmongo
knbt
knote
koalaql
koans
kobalt
kobweb
kodein
kodex
kohesive
koin
koin-dev
komapper
kondor-json
kong
kontent
kontributors
korau
korean
korge
korim
korio
korlibs
korte
kotest
kotest-contributors
kotless
kotlick
kotlin-asia
kotlin-beam
kotlin-by-example
kotlin-csv
kotlin-data-storage
kotlin-foundation
kotlin-fuel
kotlin-in-action
kotlin-inject
kotlin-latam
kotlin-logging
kotlin-multiplatform-contest
kotlin-mumbai
kotlin-native
kotlin-pakistan
kotlin-plugin
kotlin-pune
kotlin-roadmap
kotlin-samples
kotlin-sap
kotlin-serbia
kotlin-spark
kotlin-szeged
kotlin-website
kotlinacademy
kotlinbot
kotlinconf
kotlindl
kotlinforbeginners
kotlingforbeginners
kotlinlondon
kotlinmad
kotlinprogrammers
kotlinsu
kotlintest
kotlintest-devs
kotlintlv
kotlinultimatechallenge
kotlinx-datetime
kotlinx-files
kotlinx-html
kotrix
kotson
kovenant
kprompt
kraph
krawler
kroto-plus
ksp
ktcc
ktfmt
ktlint
ktor
ktp
kubed
kug-leads
kug-torino
kvision
kweb
lambdaworld_cadiz
lanark
language-evolution
language-proposals
latvia
leakcanary
leedskotlinusergroup
lets-have-fun
libgdx
libkgd
library-development
linkeddata
lithuania
london
losangeles
lottie
love
lychee
macedonia
machinelearningbawas
madrid
malaysia
mathematics
meetkotlin
memes
meta
metro-detroit
mexico
miami
micronaut
minnesota
minutest
mirror
mockk
moko
moldova
monsterpuzzle
montreal
moonbean
morocco
motionlayout
mpapt
mu
multiplatform
mumbai
munich
mvikotlin
mvrx
myndocs-oauth2-server
naming
navigation-architecture-component
nepal
new-mexico
new-zealand
newname
nigeria
nodejs
norway
npm-publish
nyc
oceania
ohio-kotlin-users
oldenburg
oolong
opensource
orbit-mvi
osgi
otpisani
package-search
pakistan
panamá
pattern-matching
pbandk
pdx
peru
philippines
phoenix
pinoy
pocketgitclient
polish
popkorn
portugal
practical-functional-programming
proguard
prozis-android-backup
pyhsikal
python
python-contributors
quasar
random
re
react
reaktive
realm
realworldkotlin
reductor
reduks
redux
redux-kotlin
refactoring-to-kotlin
reflect
refreshversions
reports
result
rethink
revolver
rhein-main
rocksdb
romania
room
rpi-pico
rsocket
russian
russian_feed
russian-kotlinasfirst
rx
rxjava
san-diego
science
scotland
scrcast
scrimage
script
scripting
seattle
serialization
server
sg-user-group
singapore
skia-wasm-interop-temp
skrape-it
slovak
snake
sofl-user-group
southafrica
spacemacs
spain
spanish
speaking
spek
spin
splitties
spotify-mobius
spring
spring-security
squarelibraries
stackoverflow
stacks
stayhungrystayfoolish
stdlib
stlouis
strife-discord-lib
strikt
students
stuttgart
sudan
swagger-gradle-codegen
swarm
sweden
swing
swiss-user-group
switzerland
talking-kotlin
tallinn
tampa
teamcity
tegal
tempe
tensorflow
terminal
test
testing
testtestest
texas
tgbotapi
thailand
tornadofx
touchlab-tools
training
tricity-kotlin-user-group
trójmiasto
truth
tunisia
turkey
turkiye
twitter-feed
uae
udacityindia
uk
ukrainian
uniflow
unkonf
uruguay
utah
uuid
vancouver
vankotlin
vertx
videos
vienna
vietnam
vim
vkug
vuejs
web-mpp
webassembly
webrtc
wimix_sentry
wwdc
zircon
Powered by Linen
coroutines
  • d

    Dariusz Kuc

    01/20/2021, 5:54 PM
    Hello 👋 Playing around with
    Channel
    based pipelines and was wondering whether you have any suggestions to make it better. NOTE: for this exercise want to stick to channels only Consider following basic example - fetch list of items and for each one of them fetch additional information (details + reviews) that will be used to final result
    val result = mutableListOf()
    
    val summaries = retrieveSummaries()
    for (summary in summaries) {
       val details = retrieveDetails(summary.id)
       val reviews = retrieveReviews(summary.id)
    
       result.add(buildResult(summary, details, reviews)
    }
    
    return result
    I could easily parallelize the above by doing something like
    summaries.map { summary -> 
      async {
        val details = async { retrieveDetails(summary.id) }
        val reviews = async { retrieveReviews(summary.id) }
        
        buildResult(summary, details.await(), reviews.await())
      }
    }
    Currently trying to figure out what would be the "best" way to achieve the same using
    Channel
    . "Simplest" would be to do a sequence of channels
    val summaries: ReceiveChannel<Summary> = summariesChannel()
    val detailsAndSummaries: ReceiveChannel<Pair<Summary, Detail>> = detailsAndSummariesChannel(summaries)
    val result: ReceiveChannel<Result> = resultChannel(detailsAndSummaries)
    Looks like
    BroadcastChannel
    is marked obsolete but I guess logically it would make sense to broadcast summaries and then send both details and reviews from separate channels but I am unsure how to read from multiple channels at once (i.e.
    buildResult
    would need results from 3 channels). Any ideas/suggestions?
    d
    j
    • 3
    • 6
  • m

    Marco Righini

    01/20/2021, 10:53 PM
    Hello, I had to use coroutines reactive but I ran in a strange behavior while testing. This is a minimal not working example
    class CoroutinesReactiveTest {
    
        private val dep = mock<Dep>()
        private val underTest = UnderTest(dep)
    
        @Test
        fun `Test someOtherMethod called`() = runBlocking {
            underTest.methodToTest().test()
    
            verify(dep).someMethod() // Commenting this line test passes
            verify(dep).suspendingFun()
            verify(dep).someOtherMethod()
        }
    }
    
    class Dep {
    
        fun someMethod() {
            println("someMethod called")
        }
    
        suspend fun suspendingFun() {
            delay(100)
            println("suspendingFun called")
        }
    
        fun someOtherMethod() {
            println("someOtherMethod called")
        }
    }
    
    class UnderTest(private val dep: Dep) {
    
        fun methodToTest(): Completable {
            return Completable.fromCallable { dep.someMethod() }
                .andThen(rxCompletable { dep.suspendingFun() })
                .andThen(Completable.fromCallable { dep.someOtherMethod() })
        }
    }
    commenting the first verify test passes
    m
    • 2
    • 6
  • j

    João Eudes Lima

    01/21/2021, 4:18 AM
    When using MutableLiveData works
    g
    • 2
    • 31
  • e

    eygraber

    01/21/2021, 9:30 PM
    If I catch a
    CancellationException
    should I rethrow it?
    d
    • 2
    • 1
  • j

    Javier

    01/21/2021, 10:01 PM
    Is it possible to
    filterNotNull
    a
    MutableStateFlow
    and keep returning a
    StateFlow
    instead of a
    Flow
    ? It is forcing me to add an
    stateIn
    to retransform the
    Flow
    into
    StateFlow
    g
    i
    • 3
    • 4
  • w

    william

    01/22/2021, 12:08 AM
    when using
    MutableSharedFlow
    is there any consequence for choosing a buffer of
    Int.MAX_VALUE
    ? i.e. does it allocate an array of that size or something? often i would like some buffer to exist but don't have a definitive size in mind so i default to max value rather than something arbitrary between
    0 .. MAX_VALUE
    g
    • 2
    • 1
  • j

    Jason

    01/22/2021, 7:16 AM
    I call this function when app startup and stuck on loading screen . Here is the log console when debug:
    Log: Before delay
    Log: Init Status: true
    Log: Job Status: true
    getUserInfo()
    will not be called at all ??? What’s happen with flow ?
    interface InitRepository {
        val initFinish: Flow<Boolean>
    }
    
    suspend fun startApp() {
    
        checkStatus()
        waitInitializeDone()  -> App is stuck on waiting here... Forever waiting
        getUserInfo()
    }
    
    
    suspend fun waitInitializeDone() {
        withContext(<http://Dispatchers.IO|Dispatchers.IO>) {
                    val waitJob = launch {
                        Log.d("Before delay")
                        delay(10000L)
                        throw TimeoutException("Init process timeout")
                    }
                    initRepository.initFinish
                        .onEach { initFinish ->
                            Log.d("Init Status: $initFinish")
                            Log.d("Job Status: ${waitJob.isActive}")
                            if (initFinish && waitJob.isActive) {
                                waitJob.cancel()
                            }
                        }
                        .launchIn(this)
                }
    }
    y
    • 2
    • 3
  • c

    christophsturm

    01/22/2021, 11:34 AM
    why does idea complain about a blocking call in this snippet?
    return@coroutineScope withContext(<http://Dispatchers.IO|Dispatchers.IO>) {
                        Files.readAllBytes(path)
                    }
    m
    e
    • 3
    • 3
  • c

    Chris Fillmore

    01/22/2021, 2:35 PM
    Hi everyone, I am doing some work with OpenGL/SurfaceTexture on Android and am considering having a dedicated thread for these operations. I have a reference implementation (written in Java) where this is the approach. Is there a more Kotlin-idiomatic way of doing this? Some alternatives I should consider? I appreciate your thoughts, thanks.
    d
    • 2
    • 2
  • f

    FunkyMuse

    01/25/2021, 10:43 AM
    Hi everyone, how do you use coroutines to tackle with the SingleLiveEvent I've tried the code below but when rotating the device the latest value is displayed, i want the value to be consumed only once just as SingleLiveEvent is
    protected val loadingState = BroadcastChannel<Boolean>(Channel.BUFFERED)
        val actionReceiver = loadingState.asFlow()
    s
    a
    o
    • 4
    • 31
  • l

    leandro

    01/25/2021, 4:06 PM
    Is there an operator to go from
    List<Flow<A>>
    to
    Flow<List<A>>
    ? I’m currently applying the following:
    .flatMapLatest { items: List<Flow<A>> ->
      combineTransform(items) {
        emit(it.toList())
      }
    }
    but am wondering if this is common enough and/or is handled in a better way with a different operator.
    w
    p
    • 3
    • 6
  • u

    ursus

    01/25/2021, 6:37 PM
    Is there a convenience to make a suspend function take atleast X ms in total? Or should I manually time it and add delay
    m
    • 2
    • 1
  • g

    gbaldeck

    01/26/2021, 1:52 AM
    Hi, I'm working with compose-desktop and coroutines. I am updating app state through a StateFlow and am a little confused about what thread the StateFlow needs to be updated on. For example, a user enters some text, a coroutine is launched to save the text to the database, then a new state object is created with the new text, the state object is then added to the StateFlow, the composable listening to the StateFlow is updated. The last part, when the state object is added to StateFlow, does that need to happen on Dispatchers.UI in stead of Dispatchers.Main because the UI will be updated?
    a
    • 2
    • 1
  • u

    ursus

    01/26/2021, 5:56 AM
    This might be slightly offtopic, but how do you unit test concurrent code? If I just let loose two threads at a function, im not guaranteed contention will happen, right?
    z
    • 2
    • 3
  • w

    WukongRework.exe

    01/26/2021, 7:17 AM
    So I was doing some tests with newSingleThreadContext and withContext and I was wondering, does withContext block the parent coroutineScope?
    import kotlinx.coroutines.*
    fun main() = runBlocking {
        launch {
            delay(100)
            println("@ launch")
        }
        withContext(newSingleThreadContext("new Context")) {
            delay(200)
            println("@ withContext")
        }
        println("@ runBlocking")
    }
    // Outputs
    @ launch
    @ withContext
    @ runBlocking
    but
    import kotlinx.coroutines.*
    
    fun main() = runBlocking {
        launch {
            delay(100)
            println("@ launch")
        }
        launch(newSingleThreadContext("new Context")) {
            delay(200)
            println("@ withContext")
        }
        println("@ runBlocking")
    }
    // Outputs
    @ runBlocking
    @ launch
    @ withContext
    could someone please explain this?
    t
    a
    • 3
    • 2
  • m

    Marc Knaup

    01/26/2021, 4:28 PM
    If some code does (de)serialization or other potentially CPU-intensive work like using a template system to build HTML (all in-memory), do you do delegate the execution to the
    Default
    dispatcher? Or do you you accept that the current dispatcher (whatever it is) is potentially blocked for a few milliseconds? I have the habit of wrapping such code in
    withContext(Dispatchers.Default) { … }
    , but I’m not actually sure if that’s necessary. Or maybe it’s even a bad idea.
    k
    c
    +2
    • 5
    • 6
  • e

    Eugen Martynov

    01/26/2021, 5:28 PM
    If I have a Cancellable implementation - can I somehow listen for the job cancellation and invoke cancel on Cancellable?
    m
    a
    +2
    • 5
    • 27
  • l

    Lucien Guimaraes

    01/26/2021, 11:16 PM
    Hi 👋 I have a question regarding multiple collectors for Flow : how do you properly implement it? I tried to transform a Flow to a SharedFlow, to be able to do so. But it's no working, only the first collector called is doing his job:
    //Inside UseCase
    suspend fun state(): SharedFlow<HomeState> = locationInteractor
        .canGetLocations
        .flatMapLatest { ... }
        .flowOn(ioDispatcher)
        .shareIn(
            scope = CoroutineScope(Job() + ioDispatcher),
            started = SharingStarted.Eagerly,
            replay = 1,
        )
    
    //Inside ViewModel
    suspend fun success(): Flow<List<HikeCard>> = homeInteractor
        .state()
        .filterIsInstance<HomeInteractor.HomeState.Success>()
        .map { ... }
    
    suspend fun error(): Flow<ErrorMessages> = homeInteractor
        .state()
        .filterIsInstance<HomeInteractor.HomeState.Error>()
        .map { ... }
    
    //Inside View
    outputs.success().collect { ... }  // the only one collected because of order
    outputs.error().collect { ... } // never collected, except if moved above previous collector
    Am I missing / misunderstanding something? Thanks for your help!
    m
    c
    • 3
    • 4
  • s

    Simon Lin

    01/27/2021, 7:33 AM
    Can I set the min interval for the downstream to consume? (using flow or channel) for example:
    k
    e
    +3
    • 6
    • 17
  • v

    Vivek Sharma

    01/27/2021, 2:49 PM
    I am reading basics of coroutines from docs, I have a doubt like :
    launch {
       doingNetworkCall()  // this is suspend function
    }
    // doing some work on main thread here like loading
    so assume doingNetworkCall() is taking some time, till that time that function get suspended OR it just works in background thread and on completion it returns like callback and do other work and if this work is getting suspended, then when it is getting resumed to achieve desired output
    c
    l
    • 3
    • 4
  • z

    Zach Klippenstein (he/him) [MOD]

    01/27/2021, 2:57 PM
    The docs on
    MutableSharedFlow
    are unclear, and I haven’t had enough coffee this morning to figure it out from looking at the code: if there’s no buffer and no replay, is there any difference between
    DROP_OLDEST
    and
    DROP_LATEST
    ? I don’t think there should be, since if there’s no buffer, and no subscriber waiting for a value at the time of emission, the only thing to do is drop the value and there’s no concept of the “oldest” or “latest” value, just “the value trying to be emitted”.
    p
    • 2
    • 4
  • v

    Vivek Sharma

    01/27/2021, 4:59 PM
    When I run the following code, the
    Job from coroutine scope
    is printed first, not
    Job1
    , why is that?
    fun main() = runBlocking<Unit> {
        launch {
            println("Job 1")
        }
    
        launch {
            println("Job 2")
        }
    
        launch {
            println("Job 3")
        }
    
        coroutineScope {
            launch {
                println("Job from launch inside coroutine scope")
            }
    
            println("Job from coroutine scope ")
        }
    }
    z
    • 2
    • 1
  • n

    neworldlt

    01/27/2021, 6:48 PM
    Hello. What is idiomatic way to merge two flows in precise positions. Assume following code:
    val flowA = (1..10).asFlow()
    val flowB = flowOf("a","b", "c", "d", "e")
    Result I want to get is:
    1, 2, a, 3, 4, b, 5, 6, c, 7, 8, d, 9, 10, e
    My current solution is to use ReceiveChannel, but it does not look very idiomatic:
    launch {
      val channelB = flowB.produceIn(this)
      flowA.withIndex().transform { item -> 
        emit(item)
        if (item.index > 0 && item.index % 2 == 1)
          emit(flowB.receive())
      }.collect { /* something useful */ }
    }
    k
    • 2
    • 2
  • j

    Jgafner

    01/28/2021, 7:34 AM
    Hi Need some help in understand some basic. I am holding a list of API requests I would like to execute in parallel. I need to wait for all the responses, each response is a list and combine all of them into one list. I still struggle to change the way I think with parallel Vs async - I ll be glad if someone can point me to a similar example in kotlin when async is used to fork and join a collection. thanks
    v
    t
    l
    • 4
    • 7
  • s

    Simon Lin

    01/29/2021, 3:34 AM
    According to the Dispatchers.IO doc:
    ... using withContext(Dispatchers.IO) { ... } does not lead to an actual switching to another thread — typically execution continues in the same thread.
    So how does it do not to blocking thread but using same thread? When does it really switch another thread? (or never?) --- Edit: The key is
    Thread pool
    ?
    👀 1
    b
    • 2
    • 1
  • s

    Slackbot

    01/29/2021, 9:27 AM
    This message was deleted.
    e
    • 2
    • 1
  • e

    Eugen Martynov

    01/29/2021, 9:30 AM
    I have
    private val testCoroutineDispatcher = TestCoroutineDispatcher()
      private val testCoroutineScope = TestCoroutineScope(testCoroutineDispatcher)
    I try to run suspend function in it
    fun runBlockingTest(block: suspend TestCoroutineScope.() -> Unit) =
        testCoroutineScope.runBlockingTest { block() }
    And particular is
    dispatcherRule.runBlockingTest {
          val msg = Gallery.Effects.LoadGallery.run.invoke(this, Gallery.Deps(photoGalleryManager))
          assertThat(msg).isEqualTo(Gallery.Msg.FilesLoaded(failure))
        }
    I’m getting
    This job is not completed yet
    Even if I change it to:
    private val testCoroutineScope = TestCoroutineScope(testCoroutineDispatcher + Job())
    I still get that exception, what can I do? If I run test inside the global scope then test pass
    b
    • 2
    • 4
  • n

    Niklas Gürtler

    01/29/2021, 10:54 AM
    Is there a common pattern for starting a coroutine, when you only ever want one or zero instances of it running? Something like
    class MyActivity {
        var coroJob : Job? = null
        val coroScope = MainScope()
      
        // Start my coroutine, may be called from any thread
        fun startCoro () {
            // coroJob should only be accessed from main thread
            coroutineScope.launch (Dispatchers.Main) {
                if (coroJob == null) {
                    coroJob = coroutineScope.launch (<http://Dispatchers.IO|Dispatchers.IO>) {
                        // Do the actual work here ...
    
                        withContext(Dispatchers.Main) {
                            coroJob = null
                        }
                    }
                }
            }
        }  
    }
    But reducing the boiler plate?
    t
    g
    • 3
    • 7
  • n

    Niklas Gürtler

    01/29/2021, 10:59 AM
    Another possibility might be
    val coroJob = AtomicReference<Job> ()
        /// Start my coroutine, may be called from any thread
        fun startCoro () {
    
            val coro = coroutineScope.launch(<http://Dispatchers.IO|Dispatchers.IO>, start = LAZY) {
                // Do the actual work here ...
                coroJob.set(null)
            }
    
            // If coroJob isn't null, do nothing.
            if (coroJob.compareAndSet(null, coro))
                coro.start()
        }
    which avoids the explicit context switches and should still be thread-safe. Is there a more idiomatic and safe way to do that?
    u
    • 2
    • 17
  • c

    christophsturm

    01/30/2021, 10:16 AM
    if i have a list of 10 deferreds, is there an easy way each one of them as soon as it completes?
    deferredList.mapResolved{deferredResult -> ... }
    a
    z
    • 3
    • 26
Powered by Linen
Title
c

christophsturm

01/30/2021, 10:16 AM
if i have a list of 10 deferreds, is there an easy way each one of them as soon as it completes?
deferredList.mapResolved{deferredResult -> ... }
if i do it like this, is there a way to be sure that my launch blocks don’t interrupt each other? I want my println output not to be mixed up by threads
suspend fun bla(deferred: List<Deferred<Context>>) {
    coroutineScope {
        deferred.forEach {
            launch {
                val context = it.await()
                println(
                    context.summary()
                )
            }
        }
        
    }
    
}
a

Arslan Armanuly

01/30/2021, 1:57 PM
if you want the several printlns behave as if they were called from the one thread, you can create
val singleThreadedContext = Executors.newSingleThreadExecutor().asCoroutineDispatcher()
and then
withContext(singleThreadedContext) {
    println(context.summary())
}
c

christophsturm

01/30/2021, 2:27 PM
Great. Will that perform better than to make the Println synchronized on context?
a

Arslan Armanuly

01/30/2021, 3:49 PM
I would recommend not using synchronized with coroutines because coroutines works on the concept of continuations and if you have suspending function call in the synchronized block, it can have undesirable behaviour
If you want the behaviour that synchronized provides, you can use
val mutex = Mutex()
mutex.withLock { /* code */ }
If you want to know more about sharing mutable state, here is great article on https://kotlinlang.org/docs/reference/coroutines/shared-mutable-state-and-concurrency.html
c

christophsturm

01/30/2021, 5:36 PM
hmm, but whats better? a task switch or a mutex? I guess the mutex will perform better. will the await change the dispatcher to the one where the deferred was resolved, or will it stay in the dispatcher of my async block?
z

Zach Klippenstein (he/him) [MOD]

01/30/2021, 5:36 PM
if i do it like this, is there a way to be sure that my launch blocks don’t interrupt each other?
You mean you want the prints to be executed in the order of the list, regardless of which order the deferreds complete in?
c

christophsturm

01/30/2021, 5:39 PM
I don’t even care about the order. i just want just one println to run at a time
each deferred is a result, the order does not matter
z

Zach Klippenstein (he/him) [MOD]

01/30/2021, 5:40 PM
The code you wrote will definitely do that. And it will also do so in the same order, that of the list, every time. There’s no magic going on here.
c

christophsturm

01/30/2021, 5:41 PM
well it will print each result as soon as the deferred is ready
z

Zach Klippenstein (he/him) [MOD]

01/30/2021, 5:41 PM
The first iteration of the loop waits for the first deferred to complete. It doesn’t wait for or know about any of the other deferreds. Only when the first deferred completes, then the print, then the next deferred is awaited on, etc
c

christophsturm

01/30/2021, 5:41 PM
if they all are already ready it will be the order of the list
z

Zach Klippenstein (he/him) [MOD]

01/30/2021, 5:41 PM
Oh derp I missed the launch
Ok then the mutex solution makes sense. Although you could also convert your deferreds to Flows and use the merge operator
You could also create a channel, then from your launched coroutines send the results into the channel, and in your main coroutine, receive from the channel in a loop
c

christophsturm

01/30/2021, 5:45 PM
it was a channel at some point then i converted it to a list of deferreds
but now i want to print the deferreds as soon as they are ready so maybe deferreds are not the best solution anymore
z

Zach Klippenstein (he/him) [MOD]

01/30/2021, 5:46 PM
What’s your producer code look like?
c

christophsturm

01/30/2021, 5:48 PM
https://github.com/christophsturm/failfast/blob/main/failfast/src/main/kotlin/failfast/Suite.kt#L49
right now contextExecutor returns a list of deferred (one for each test context). and those each contain a list of deferred for each test result. and I’m now printing the results for each context when all the test of that context are finished
so its a bit more complicated than my example
z

Zach Klippenstein (he/him) [MOD]

01/30/2021, 8:05 PM
Hm, I don’t think anything there requires syncrhonization. You have a single print call per launched coroutine, and i believe print is effectively atomic on most systems.
that
asSequence()
call on
contextInfos
looks redundant though,
List
has
forEach
as well
c

christophsturm

01/30/2021, 10:03 PM
i guess if println is not guaranteed to be atomic i can just wrap it with a mutex anyway
View count: 2