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

    marcinmoskala

    01/27/2022, 5:18 PM
    Is there a difference between 
    <http://Dispatchers.IO|Dispatchers.IO>.limitedParalellism(100)
    and
    Dispatchers.Default.limitedParalellism(100)
    ?
    j
    j
    b
    • 4
    • 6
  • d

    dimsuz

    01/28/2022, 1:04 PM
    Trying to come up with good way to suspend until the first emission from the flow which is launched in parallel. app code:
    class Feature  {
       private val scope = CoroutineScope()
       private val _flow = MutableSharedFlow<Int>()
       
       fun start() {
         scope.launch { flow.emit(1); flow.emit(2) }
       }
    
       val flow: Flow<Int> = _flow
    }
    test code:
    should("do something") {
     val awaitFirstEmit = feature.flow.onStart { feature.start() }.first()
     awaitFirstEmit shouldBe 1
    }
    Is it OK to use
    onStart
    like this, or will this produce flakiness? the important thing here is I want to ensure that first item is not lost.
    j
    n
    • 3
    • 8
  • t

    trevjones

    01/29/2022, 1:00 AM
    New drinking game: When migrating from
    runBlockingTest
    to
    runTest
    . For each test you get to pass, take a drink!
    b
    • 2
    • 1
  • a

    Arjan van Wieringen

    01/30/2022, 10:03 AM
    I thought I'd get started with the actors, but I notice they are only implemented for the JVM. Shame. Any chance this might change in the future?
    • 1
    • 1
  • a

    AKlam

    01/31/2022, 2:36 PM
    Hi everyone! How Flow.sample() should be tested with kotlinx-coroutines-test 1.6.0? Every time I run attached test it runs infinitely 🙈
    SomeTest.kt
    ➕ 1
    b
    n
    • 3
    • 7
  • c

    Ciprian Grigor

    01/31/2022, 4:37 PM
    Is there a guide how to test in memory room database with coroutines especially using new test coroutine api added in kotlin 1.6 ?
    y
    g
    • 3
    • 3
  • r

    Roudy Korkis Kanaan

    02/01/2022, 4:43 AM
    Hello everyone! I'm trying to migrate to 1.6.10 coroutines-test and have a ViewModel that contains a flow using the
    mapLatest
    operator. More details in the thread with code examples.
    👀 1
    n
    • 2
    • 5
  • m

    Marko Novakovic

    02/01/2022, 4:54 PM
    how to combine two `SharedFlow`s into
    Flow
    that emits when either
    SharedFlow
    emits?
    f
    c
    • 3
    • 6
  • a

    aballano

    02/01/2022, 6:11 PM
    Hello there, I was recently bitten by the
    MutableSharedFlow
    default constructor + tryEmit issue. I was reading through the issue and seems to me that the docs added here are not 100% accurate? It seems to me that they indicate that the
    tryEmit
    call can succeed, but in reality it will always fail (aka not emit anything) but can return true or false depending on having subscribers or not, isn’t it? cc @elizarov Wondering if it would make sense to have a quick PR there to simplify the texting, could volunteer for that 🙂
    b
    • 2
    • 3
  • f

    flygerian.eagle

    02/02/2022, 4:11 AM
    Hi, I'm Ini... I recently hopped on the kotlin boat ⛵ I'm using 'kotlin apprentice' as a reference - by R. Wenderlich - currently I'm studying coroutines... My issue: kotlinx dependency isn't building...so I used Retrofit dep (build.gradle) cuz Retro includes coroutines out of the box 🎁 Retro dep builds...autocomplete for kotlinx.coroutines.* works, yet features are red - dispatchers, launch, run blocking etc... I'll search to see if anyone else has this problem here anyways I'm proud to meet you guys and I hope we can do some work - good work together! #coroutines
    j
    n
    l
    • 4
    • 9
  • u

    ubu

    02/02/2022, 12:56 PM
    Sequential_coroutines_FAQ
    d
    j
    n
    • 4
    • 8
  • b

    brabo-hi

    02/02/2022, 5:40 PM
    Hi all, from the doc
    *Warning:* Never collect a flow from the UI directly from *launch* or the *launchIn* extension function if the UI needs to be updated. These functions process events even when the view is not visible. This behavior can lead to app crashes. To avoid that, use the *repeatOnLifecycle* API as shown above.
    What is the safest way to collect stateFlow in compose since we don’t have access to `*`repeatOnLifecycle`*` since it is not recommended to collect using
    launch
    ?
    t
    i
    +2
    • 5
    • 9
  • d

    dimsuz

    02/03/2022, 11:38 AM
    Is there a nice way to combine 2 state flows into another one without using
    stateIn
    which requires a
    CoroutineScope
    ?
    val s1: StateFlow<Int>
    val s2: StateFlow<Long>
    
    val s3: StateFlow<Long> = combine(s1, s2) { v1, v2 ->
      v1.toLong() + v2
    }
    // ^^^ can't do that, combine results in `Flow<Long>`, 
    // must do stateIn...
    j
    g
    d
    • 4
    • 11
  • d

    dimsuz

    02/03/2022, 1:46 PM
    Am I missing something or there's no version of zip for 3,4,5, iterable flows? there is a top-level
    combine
    , but no top-level
    zip
    . I have a
    List<Flow<Int>>
    and want to zip them, what is my best option?
    g
    e
    • 3
    • 28
  • l

    Lukasz Kalnik

    02/03/2022, 2:56 PM
    I'm migrating a test to coroutines 1.6.0 which should check that a suspending function throws an exception. I'm using AssertJ for assertions. This is what the test looked like before:
    @Test
    fun `when no gateway from scanning present then throw`() {
        every { state.gateway } returns null
    
        assertThatIllegalStateException().isThrownBy { runBlocking { useCase.execute(Params()) } }
    }
    This is what it looks like after the migration, according to the official migration guide:
    val exceptions = mutableListOf<Throwable>()
        val customCaptor = CoroutineExceptionHandler { _, throwable ->
            exceptions.add(throwable)
        }
    
        @Test
        fun `when no gateway from scanning present then throw`() = runTest {
            every { state.gateway } returns null
    
            launch(customCaptor) {
                useCase.execute(Params())
            }
            advanceUntilIdle()
    
            assertThat(exceptions).hasSize(1)
                .first().isInstanceOf(IllegalStateException::class.java)
        }
    However, the exception is for some reason not caught by the
    customCaptor
    , but thrown in the test and the test fails.
    d
    • 2
    • 18
  • p

    Paul Woitaschek

    02/03/2022, 3:36 PM
    I don’t quite get it with the docs on
    Deferred
    For
    await
    , it says:
    […] If the Job of the current coroutine is cancelled or completed while this suspending function is waiting, this function immediately resumes with CancellationException. […]
    Why would the await function resume with a CancellationException if the job completes while await is waiting?
    j
    n
    • 3
    • 4
  • g

    George

    02/04/2022, 8:42 AM
    Hi, im new to kotlin coroutines and after a look in the docs i have a question, in case i have spring boot app (actually whatever app it doesnt matter) and lets say i have a rest api, something like this:
    //@RestController
    //@RequestMapping("${v1}/ping")
    public class TestController {
    
        @GetMapping(value = ["", "/"])
        public suspend fun testAsync(): Deferred<ApiResponse> {
            coroutineScope {
                // add here launch, async etc   
            }
        }
    
    }
    For every api should i add a coroutineScope to achieve structured concurrency ?
    s
    j
    k
    • 4
    • 12
  • a

    aballano

    02/04/2022, 4:29 PM
    Hello folks, I have a case where I’m collecting a flow to do some operations but on every emission I need to do a side effect and have another different flow to observe until there’s a new value emitted. I was thinking on using flatMapLatest but that would multiply the initial emission every time the internal one emits something + would get delayed, so I though about doing a
    onEachLatest
    sort of 🤔 Sharing here for feedback or in case I’m missing something 😬
    @ExperimentalCoroutinesApi
    public fun <T> Flow<T>.onEachLatest(action: suspend (T) -> Unit): Flow<T> = transformLatest { value ->
        action(value)
        return@transformLatest emit(value)
    }
    the only real difference with
    onEach
    is the
    transform
    ->
    transformLatest
    but I guess that should work, right?
    n
    • 2
    • 2
  • t

    tomas-mrkvička

    02/04/2022, 8:46 PM
    Hello guys. I am struggling with
    runBlocking
    . The documentation says that it should be used in
    main
    , tests and libraries to bridge two worlds. I found zero information about structured concurrency within plain command line applications. Lets say I have a tool which migrates data from one source to another and I would like to use concurrent executions for some parts of the whole migration process. Now, should I define
    runBlocking
    somewhere "in the middle", or how to use coroutines in the world where no life cycle managers exists? Thanks
    n
    j
    +3
    • 6
    • 17
  • g

    George

    02/06/2022, 3:21 PM
    Hi guys, I have a question, in case i use async inside a coroutinescope but I await it outside the scope is it ok to do so or is there something like a deadlock where the actual computation will happen inside the scope and the rest code will complete sequential no matter where I await for it ?
    n
    • 2
    • 6
  • o

    oday

    02/06/2022, 7:04 PM
    I’m having a weird issue where IntelliJ IDEA always forces this import when attempting to resolve
    launch{}
    ->
    import javafx.application.Application.launch
    y
    j
    • 3
    • 5
  • l

    Lukasz Kalnik

    02/07/2022, 6:06 PM
    I have a test where a flow should emit with delay, but it doesn't emit:
    @Test
    fun `test flow`() = runTest {
        val eventUpdateService = mockk { 
            every { subscribeToEvents() } returns flowOf(SomeEvent).onStart { delay(1000) } 
        }
        val presenter = Presenter(
            UnconfinedTestDispatcher(),
            eventUpdateService
        )
        presenter.attachView(view)
        advanceTimeBy(2000)
        verify { view.displayEvent() } // fails because the flow didn't emit
    }
    
    class Presenter(
        coroutineContext: CoroutineContext,
        val eventUpdateService: EventUpdateService    
    ) {
    
        val coroutineScope = CoroutineScope(coroutineContext)
    
        fun attachView(view: View) {
            coroutineScope.launch {
                eventUpdateService.subscribeToEvents().collect { event ->
                    view.displayEvent()
                }
            }
        }
    }
    j
    n
    • 3
    • 19
  • l

    Lukasz Kalnik

    02/08/2022, 12:28 PM
    What is actually the difference between
    StandardTestDispatcher
    and
    UnconfinedTestDispatcher
    in a case where you always inject a dispatcher in the system under test? Let's say we have a presenter, like in my post above, which always uses one dispatcher for all coroutine calls (e.g.
    Dispatchers.Default
    ). For tests it gets injected a test dispatcher, so during tests every coroutine launched inside the presenter uses this injected dispatcher. Is there a difference which dispatcher is used then?
    j
    d
    • 3
    • 29
  • m

    Mini

    02/08/2022, 7:11 PM
    Im struggling to understand why .map and .combine works differently with .stateIn in my tests The test testing .map works as expected, the one testing the combine does not.
    n
    • 2
    • 2
  • t

    Tomer Abramovich

    02/09/2022, 6:54 AM
    hi, new to kotlin, so bear with me... i'm building a library which relies on coroutine context (via suspend functions) to propagate "sticky" information such as tenant id etc. what is the best way for the caller of my library function to pass the tenant information on the context?
    suspend fun myLibraryFunction(query : Query) : QueryResult{
      val requestContext: RequestContext = currentCoroutineContext()[RequestContext]!! //expecting a dedicated context element
      val tenantId = requestContext.tenantId
      do something with tenantId
    }
    
    suspend callerFunction () {
      val requestContext = RequestContext(tenantId)
      CoroutineScope(requestContext).async { myLibraryFunction(query) }.await()
    }
    ^^^ This is what i came up with, but it seems redundant to create a new coroutine (i.e async) i just want the user to be able to set the requestContext on the current context and that the called function will inherit that something like
    suspend fun callerFunction () : QueryResult {
      val requestContext = RequestContext(tenantId)
      currentCoroutineContext().plus(requestContext) //i know it's immutable so won't work
      myLibraryFunction(query)
    }
    b
    • 2
    • 4
  • b

    brabo-hi

    02/09/2022, 6:07 PM
    Hi all, from the doc WorkManager invokes ListenableWorker.onStopped() as soon as your Worker has been stopped. Override this method to close any resources you may be holding onto. How could we override
    onStopped
    since on
    CoroutineWorker
    it is defined
    public final override fun onStopped() {}
    l
    • 2
    • 1
  • t

    Tim Malseed

    02/09/2022, 10:38 PM
    Can someone help me understand.. If I want to create a
    StateFlow
    , I can call
    MutableStateFlow()
    . But, if I want to convert a Flow into a
    StateFlow
    , I call
    stateIn()
    .
    stateIn()
    requires a
    CoroutineScope
    . But
    MutableStateFlow()
    doesn’t. Why is that?
    j
    z
    • 3
    • 3
  • k

    K Merle

    02/10/2022, 5:57 AM
    Is there a reason why combine flow would not emit end result?
    val x = combine(y.invoke(), z.invoke()){ y+z }
    Both
    y
    and
    z
    are flows of same type and they seem to not throw any errors.
    b
    f
    • 3
    • 5
  • s

    stojan

    02/10/2022, 10:12 AM
    is there a function in the coroutines lib that transforms a
    List<Flow<T>>
    to
    Flow<List<T>>
    ?
    e
    h
    • 3
    • 9
  • s

    Shaheer Muzammil

    02/10/2022, 11:01 AM
    Is it correct to use ConcurrentHashMaps in the context of multiple coroutines? As in multiple coroutines can essentially run in a single thread and these data structures are thread safe, but in case multiple coroutines are running on that same thread. Would it be safe then?
    e
    o
    • 3
    • 4
Powered by Linen
Title
s

Shaheer Muzammil

02/10/2022, 11:01 AM
Is it correct to use ConcurrentHashMaps in the context of multiple coroutines? As in multiple coroutines can essentially run in a single thread and these data structures are thread safe, but in case multiple coroutines are running on that same thread. Would it be safe then?
e

ephemient

02/10/2022, 11:04 AM
coroutines can only switch at suspend points which only occur in Kotlin code; Java code always runs sequentially
👍 1
so if you're doing something like
map[key]
in a single-threaded dispatcher, sure that's safe
but if you're doing
map[key] = map[key] + foo()
where
foo()
is a suspending function, that's potentially problematic (just as in threaded code)
o

Oliver.O

02/10/2022, 11:07 AM
So it's generally single-threaded: yes, safe, but unnecessary, multi-threaded: yes, safe.
👍 1
View count: 8