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

    ghosalmartin

    01/11/2022, 8:54 AM
    I have an actor, i dispatch a message to it that contains a suspending lambda, that lambas operation dispatches more messages to the actor, but they never seem to arrive. is that because the actor is still busy processing the first message which is waiting for the suspending lambda to complete?
    z
    • 2
    • 5
  • m

    marcinmoskala

    01/11/2022, 9:03 AM
    Am I the only one who thinks it is strange you cannot close
    MutableSharedFlow
    ? Seems that cancelling all listeners (so parent scope) is the only way for this program to close 😛 https://pl.kotl.in/EzyFeqARz
    j
    g
    +2
    • 5
    • 5
  • t

    Trevor Stone

    01/11/2022, 5:26 PM
    It seems
    SharingStarted.WhileSubscribed()
    isn't working on 1.6.0-native-mt on iOS
    p
    v
    • 3
    • 7
  • e

    Exerosis

    01/11/2022, 10:24 PM
    Can anyone recommend any resources that cover the internal implementation of courotines? I've been using suspendCoroutineUninterceptedOrReturn in my networking library. When I made it I looked into what suspending functions compiled down to, so I know that at least at some point in the past a suspend function was basically a function that takes a continuation and has a big switch statement over continuation.label which it uses to determine where it will resume from each time it gets called. Even if this is still true I don't fully understand how the continuation itself is created and how confined vs unconfined works etc. The actual issue I'm having is understanding where exceptions end up going since it seems to be based on what scope is being used or something along those lines.
    e
    n
    • 3
    • 14
  • d

    dimsuz

    01/13/2022, 9:25 AM
    If I have a
    CoroutineScope
    and then I have dynamically created another scope, how could I add this scope to the first scope, so that second is cancelled along with the first?
    j
    n
    • 3
    • 10
  • d

    dimsuz

    01/13/2022, 11:36 AM
    Is there a nice way to convert replaying Flow into a non replaying? A naive implementation using
    drop(1)
    makes subscriber loose first emitted item:
    val flow = MutableSharedFlow<Int>(replay = 1)
      fun get(replayLast: Boolean): Flow<Int> = flow.drop(1) // naive impl
    
      launch { get(replayLast = false).collect { println(it} } } // doesn't receive 1
      launch { delay(1000); flow.emit(1) }
    Is having two separate flows: one with replay and one witout - the only option?
    b
    • 2
    • 6
  • t

    Tower Guidev2

    01/13/2022, 1:30 PM
    Hi im attempting to use
    private val mutableDisplayedPageNoState = MutableSharedFlow<Int>(replay = 0, extraBufferCapacity = 3, onBufferOverflow = BufferOverflow.DROP_OLDEST)
    • 1
    • 3
  • b

    bezrukov

    01/14/2022, 2:22 PM
    Is it possible to test actors (or more generally infinity loops) with a TestScope without creating a separate Job for an actor's owner (with the following cancellation before runTest completes)?
    a
    • 2
    • 3
  • t

    The Monster

    01/15/2022, 2:53 PM
    I want
    scanAudios()
    and
    scanVideos()
    to execute first before other stuff in this function.
    private suspend fun getFolderDataList(): List<FolderData> {
            thisScope.async() {
                scanAudios()
                scanVideos()
            }.await()
    
            val audioFolderData = viewModel.getAudioUris().map { uri ->
                FolderData("Audio", uri)
            }
    
            val videoFolderData = viewModel.getVideoUris().map { uri ->
                FolderData("Video", uri)
            }
    
            return audioFolderData.plus(videoFolderData)
        }
    Am I doing it correctly?
    d
    j
    • 3
    • 26
  • d

    dimsuz

    01/16/2022, 6:01 PM
    I have recently read an article which suggests that SupervisorJob shouldn't be used and CoroutineScope with proper try/catch (which is more mallable for your usecase) should be used instead (see SupervisorJob section there). On one hand I find this is true, but I still keep thinking that SupervisorJob is useful in scenarios where you specifically manage some task-like coroutine executions. What do you think?
    f
    n
    • 3
    • 6
  • k

    K Merle

    01/17/2022, 5:45 AM
    combine(
        flowOne(),
        flowTwo(),
        flowThree()
    ) { _, _, flowThree->
        flowThree
    }.stateIn(
        viewModelScope + ioDispatcher,
        SharingStarted.WhileSubscribed(NETWORK_RESULT_SHARING_TIMEOUT),
        Result.Loading
    )
    Should 
    flowThree
     emit values here when collected? FlowThree should emit every time flowOne() or flowTwo() emit values.
    g
    f
    • 3
    • 23
  • b

    benkuly

    01/17/2022, 1:31 PM
    flow.flatMapLatest { flowValue -> 
        stateFlowDependingOnFlowValue(flow1Value,scope) // internally does something like `.stateIn(scope)`
    }
    Given this code, every time
    flatMapLatest
    is called, a new coroutine is spawned in the scope. Is there a way to use a scope, which is only active within
    flatMapLatest
    , so old calculations would be cancelled?
    b
    • 2
    • 5
  • d

    dimsuz

    01/18/2022, 5:52 PM
    there was some handy function to suspend coroutine forever until cancellation will be triggered. can't find it right away, does anyone remember?
    z
    • 2
    • 2
  • p

    Paul Woitaschek

    01/18/2022, 9:42 PM
    Kind of a design question that is enabled by coroutines semantics:
    /**
       * This function returns once a shake was detected
       */
      suspend fun detect() {
        val sensorManager = context.getSystemService(Context.SENSOR_SERVICE) as SensorManager?
          ?: awaitCancellation()
        val shakeDetected = CompletableDeferred<Unit>()
        val listener = SeismicShakeDetector.Listener {
          shakeDetected.complete(Unit)
        }
        val shakeDetector = SeismicShakeDetector(listener)
        try {
          shakeDetector.start(sensorManager)
          shakeDetected.await()
        } finally {
          shakeDetector.stop()
        }
      }
    I’ve written this function that suspend until a shake was detected. Do you think such a usage of coroutines makes sense? It feels kind of unintuitive in terms of ergonomics of a regular function
    m
    a
    +2
    • 5
    • 13
  • n

    Neil Marietta

    01/19/2022, 10:19 AM
    Is it ok, even if not recommended, to use Kotlin 1.6.10 and Coroutines 1.5.2 together?
    c
    g
    • 3
    • 7
  • u

    ubu

    01/19/2022, 3:31 PM
    Hello there! I’m looking for a right operator to implement the following logic: I need to make a request to load an object. Basically, it’s a class with some fields. Then I need to subscribe to the changes relative to this object. These are granular changes — transformations applied to some of the fields of this object.
    fun loadObject(id: Id) : Flow<Object>
    fun subscribe(id: Id) : Flow<List<SubscriptionEvent>>
    First, I tried to use
    combine
    operator in the following manner:
    loadObject(id).combine(subscribe(id)) {  obj, events ->
            var result = obj
            events.forEach { event ->
                result = when (event) {
                    is Init -> {
                        obj
                    }
                    is Amend -> {
                        result.amend(event.diff)
                    }
                    is Set -> {
                        event.data
                    }
                    is SubscriptionEvent.Unset -> {
                        result.unset(event.keys)
                    }
                }
            }
            result
        }
    But this doesn’t work, obviously, since in the flow, there is always initial object (emitted only once after loading), which is combined with latest events / transformations, whereas what I need is something like
    scan
    operator, where I could first initialize (load) my object, then start consuming events, which lead to the transformation of this object. Observers will receive something like: “object in initial state, after loaded”, “object with the first sets of transformations applied”, “object with the first and second set of transformations applied”. Is there something like:
    transformations.scan(initialObjectFlow) { latestVersionOfTheObject, events -> 
    // apply new events / transformations
    // emit new version of the object 
     }
    Thank you!
    b
    e
    j
    • 4
    • 9
  • n

    natario1

    01/19/2022, 4:30 PM
    Is it safe to combine a flow with something derived from itself? Stupid example:
    val data: Flow<String?> = ....
    val hasData: Flow<Boolean> = data.map { it != null }
    val combined = data.combine(hasData) { data, hasData -> 
        require(data == null || hasData)
    }
    Note that hasData does not suspend, and let's assume flow will be collected on a single thread dispatcher.
    e
    t
    n
    • 4
    • 6
  • s

    Stylianos Gakis

    01/19/2022, 7:15 PM
    Use case: I want a flow of events from a callback based API. But whenever there is a new value incoming, I need to call a suspending function (may make a network request). However this callback is not suspending, so I am not in a suspending context. More details in thread 🧵
    j
    h
    +2
    • 5
    • 7
  • b

    Brian Guertin

    01/19/2022, 8:53 PM
    Is there anyway to set
    NSThread.stackSize
    when using coroutines? Is NSThread even used? I'm trying to workaround a stack overflow in kotlinx.serialization. But how can I increase Worker stack size? Is it possible? https://youtrack.jetbrains.com/issue/KT-50870
    g
    • 2
    • 1
  • s

    Stylianos Gakis

    01/19/2022, 10:28 PM
    This section in the coroutines documentation mention that all suspending functions inside
    kotlinx.coroutines
    is cancellable. At first I thought at any suspension point, if the current context is cancelled it would not enter, but this wording makes it sound like it’s not like that. Does this mean that potentially, if one made a series of suspending functions that are all not manually cooperating with cancellation (say all of them call blocking code, and/or other suspending functions that only call blocking code) cancellation would not happen and the suspending functions would keep alive?
    p
    e
    • 3
    • 4
  • j

    Jérémy CROS

    01/21/2022, 1:53 PM
    Hello guys! 🙂 I’m in the process of migrating to the new test api with
    runTest
    and it’s been an extremely frustrating process so far 😞 I have a very simple view model that doesn’t do a whole lot, something like :
    fun registerStuff() {
        viewModelScope.launch {
            registerStuffUseCase.execute()
        }
    }
    And a very simple test (with mockk)
    @Before
        fun setup() {
            Dispatchers.setMain(StandardTestDispatcher())
        }
    
        @Test
        fun `SHOULD fetch stuff WHEN called`() =
            runTest {
                // arrange
                val registerStuffUseCase = mockk<RegisterStuffUseCase>(relaxed = true)
                val viewModel = ViewModel(registerStuffUseCase)
    
                // act
                viewModel.registerStuff()
    
                // assert
                coVerify(exactly = 1) { registerStuffUseCase.execute() }
            }
    And it just doesn’t work. 100% of the time, verify is called before the use case is executed and the test fails. * unless * I add a
    advanceUntillIdle()
    after calling the VM... Which I can do but that’s like a hundred tests to update and I’m not even sure I’m doing things properly... Anything obvious I’m missing?
    b
    m
    +2
    • 5
    • 17
  • p

    pablisco

    01/24/2022, 2:59 PM
    I was wondering. Is this:
    flow.flatMapLatest {
      flow {
        emit("a")
        emit("b")
        emitAll(otherFlow())
      }
    }
    the same as this?
    flow.transformLatest {
      emit("a")
      emit("b")
      emitAll(otherFlow())
    }
    They seem to do the same on paper (minus the extra flow object), however, is there anything that using
    flatMapLatest
    will do that
    transformLatest
    doesn’t? 🙂
    j
    • 2
    • 3
  • b

    brabo-hi

    01/25/2022, 12:12 AM
    Hi all, how to catch exception thrown by
    callbackFlow
    ?
    fun connect():Flow<Item> = callbackFlow {
        check(1 == 0) // This is expected to throw an IllegalStateException
    }
    l
    e
    • 3
    • 4
  • l

    Lukasz Kalnik

    01/25/2022, 1:07 PM
    I have the following Presenter class and test setup for it:
    class Presenter(
        val api: Api,
        coroutineContext: CoroutineContext
    ) {
    
        val coroutineScope = CoroutineScope(coroutineContext)
    
        fun onAttachView(view View) {
            coroutineScope.launch {
                api.getDetail()
            }
        }
    }
    Test:
    import io.mockk.*
    
    class PresenterTest {
    
        val testCoroutineScope = TestCoroutineScope()
    
        val presenter = Presenter(
            api = mockk(),
            coroutineContext = testCoroutineScope.coroutineContext
        )
        val view = mockk()
    
        @AfterEach
        fun tearDown() {
            testCoroutineScope.cleanupTestCoroutines()
        }
    
        @Test
        fun `when view attached then call API`() {
            presenter.test().attachView(view)
    
            coVerify { api.getData() }
        }
    }
    How do I migrate it to coroutine-test 1.6.0?
    • 1
    • 3
  • j

    Justin Tullgren

    01/25/2022, 7:52 PM
    Hi, I can't find how to remove a subscriber to a StateFlow since collect never terminates. I just want to stop listening once a certain state is emitted. Thanks
    scope.launch { stateFlow.collect { if (it is State) doWork(); /* how do i unsubscribe here? */ } }
    j
    n
    • 3
    • 11
  • p

    PHondogo

    01/26/2022, 9:10 AM
    Hello! Does Kotlin Flow has collectLatest function but without cancelling current block?
    b
    • 2
    • 2
  • a

    Arun Joseph

    01/26/2022, 3:56 PM
    Is there anything particularly special with vmScope.coroutineContext? When I use CoroutineScope(job + vmScope.coroutineContext) to launch coroutine and use job.cancel() it doesn't cancel the coroutine. This is an example https://pl.kotl.in/e0WxVRCBt which is able to cancel with another context in place of vmScope.coroutineContext
    b
    • 2
    • 6
  • h

    hfhbd

    01/26/2022, 5:13 PM
    How can you emit (infinite) values before the real flow emits? I want to combine two flows: flow b into flow a. Flow a should not wait until the first emission of flow b, but should emit
    null
    until b emits values. After b emits some values, the last value of b should be used (combine).
    j
    e
    • 3
    • 10
  • s

    Slackbot

    01/26/2022, 8:59 PM
    This message was deleted.
    e
    u
    • 3
    • 2
  • u

    ubu

    01/26/2022, 9:06 PM
    Shared_state_and_concurrency
    e
    • 2
    • 5
Powered by Linen
Title
u

ubu

01/26/2022, 9:06 PM
Shared_state_and_concurrency
e

ephemient

01/26/2022, 9:08 PM
a post is not a text snippet - Slack has hidden that away under "Browse all shortcuts" unfortunately. but anyhow…
it is not safe to read from a map that is being updated concurrently
u

ubu

01/26/2022, 9:16 PM
do you mean that I should update getMethod or the whole paradigm (switching to actors, for instance)?
e

ephemient

01/26/2022, 9:17 PM
get() should also be synchronized on the same mutex
either that or use a different structure which is safe to access concurrently (Java has ConcurrentMap for example, but an actor publishing a whole new map on each update is also a possibility)
👍 1
View count: 2