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

    Arjan van Wieringen

    07/03/2022, 2:38 PM
    I am writing some extension functions to work with
    Flow
    and platform-specific API's, e.g. the web broadcastchannel API. However I choose to pass
    CoroutineScope
    when needed, but this leads to code like this:
    states.broadcast(channel.deserialize(scope), scope)
    Is it a code smell to have these kind of scopes everywhere? Or is it not a problem. My intuition says that it is not a problem, because this way I can easily control the scopes and no magic happens. So I can keep the structured concurrency.
  • o

    oday

    07/03/2022, 3:44 PM
    so I have this block of code
    lifecycleScope.launch {
        repeatOnLifecycle(Lifecycle.State.STARTED) {
            viewModel.uiState.collect { uiState ->
                if (uiState.authenticated) {
                    setContent {
                        Home()
                    }
                } else {
                    setContent {
                        Authentication()
                    }
                }
            }
        }
    }
    and the issue is that it’s collecting the stateFlow immediately before my viewModel gets the chance return the result, so it shows Authentication, then when the value comes back ti shows Home again I want it to…well observe like LiveData does
    a
    29 replies · 2 participants
  • p

    Philipp Kleber

    07/03/2022, 4:37 PM
    Hi, the docs of
    Flow#shareIn
    mention, that using
    buffer(0).shareIn(scope, started, 0)
    makes upstream suspend until all subscribers have processed the value. My question is whether that still holds true for
    replay > 0
    (for all currently active subscribers).
    1 reply · 1 participant
  • r

    reactormonk

    07/04/2022, 8:35 AM
    I've got a callback that can be called multiple times. How do I push the data passed to the callback into a
    Channel
    ?
    j
    4 replies · 2 participants
  • r

    Ruben Quadros

    07/04/2022, 9:35 AM
    Hi everyone, what is the difference channel
    receiveAsFlow
    vs
    consumeAsFlow
    ?
    receiveAsFlow
    can have multiple collectors and
    consumeAsFlow
    only 1?
    s
    1 reply · 2 participants
  • r

    reactormonk

    07/04/2022, 12:43 PM
    I'm building a little helper on top of a callback routine via
    suspendCoroutine
    - but the code has some rather strict timing constraints, aka one code block should fully exit before another of the same kind should enter - how would I enforce that? Code looks like this:
    suspend fun BluetoothReader.transmitEscapeCommandS(input: ByteArray): CommandAPDU {
        return suspendCoroutine { block ->
            if (this.transmitEscapeCommand(input)) {
                this.setOnEscapeResponseAvailableListener { _, response, errorCode ->
                    if (errorCode == 0) {
                        block.resume(CommandAPDU(response))
                    } else {
                        block.resumeWithException(ReaderCommandException("Error code from reader: $errorCode"))
                    }
                    this.setOnEscapeResponseAvailableListener(null)
                }
            } else {
                block.resumeWithException(ReaderCommandException("Couldn't send command. Bonded?"))
            }
        }
    }
    The listener can only really be set once, so there's a bit of a race condition there.
    j
    36 replies · 2 participants
  • j

    janvladimirmostert

    07/04/2022, 10:05 PM
    Should supervisorScope be inside launch or outside launch or doesn't it matter?
    supervisorScope {
       launch(Dispatchers.Default) {
          supervisorScope {
    j
    3 replies · 2 participants
  • p

    Pablo

    07/05/2022, 9:17 AM
    Hello how can I transform a callback to a suspend fun?
    interface Foo<T> {
      fun onSuccess(lis: (T?) -> Unit)
    }
    I'm trying to do something like this :
    suspend fun getFoo(): Bar {
       suspendCoroutine<Bar?> { continuation -> 
         val listener = object : Foo<Bar?> {
            override fun onSuccess(lis: (Bar?) -> Unit) { }
         }
    }
    But I don't know how to return a Bar
    j
    1 reply · 2 participants
  • a

    Ahmed Ibrahim

    07/05/2022, 12:18 PM
    I'm migrating to the new test coroutine API, and my tests that used to work using pause/resumeDispatcher aren't passing any more, eventhough I'm using
    runCurrent
    . So the problem, is that I have a ViewModel, that exposes a
    StateFlow<MyState
    , that's backed by
    combine(flow1, flow2...
    , I'm trying to assert the intermediate states that should be emitted, yet only the initial and the last state got emitted. Any idea what I'm doing wrong? (code in 🧵)
    j
    n
    10 replies · 3 participants
  • r

    reactormonk

    07/07/2022, 1:05 PM
    Is there an equivalent
    trySendBlocking
    to send exceptions down the channel?
    j
    s
    16 replies · 3 participants
  • r

    reactormonk

    07/07/2022, 5:43 PM
    Is there a
    mapWithState
    or similar for Channels, where I can keep a consistent state around?
    j
    6 replies · 2 participants
  • l

    liminal

    07/07/2022, 5:49 PM
    My stackoverflow question didn't get any traction so I am hoping that someone will help here https://stackoverflow.com/questions/72843100/kotlin-flow-emit-loading-state-for-every-emission
    u
    4 replies · 2 participants
  • k

    KayCee

    07/08/2022, 3:48 AM
    Can anyone help me with this. I want to achieve something like this: fisrtApiCall -> secondApiCall() -> thirdApiCall() ->.. each api call if it fails then do the next one and if it succedd then finish with a function? How can I wrap this ideas with coroutines. My current code with rx single<> is quite messy.
    u
    3 replies · 2 participants
  • e

    Exerosis

    07/09/2022, 1:42 AM
    What is a good way to schedule a repeating task in a platform agnostic way?
    fun main() = runBlocking {
        val component = Component {
            var a = 0; var b = 0
            every(50.milliseconds) {
                if (it % 20 == 0) println("A: ${a++}")
            }
            every(1.seconds) {
                println("B: ${b++}")
            }
        }
        component.enable()
        delay(50.seconds)
        println("Done!")
    }
    context(Toggled) @Base
    suspend fun every(period: Duration, block: suspend (Int) -> (Unit)) {
        simultaneously {
            var i = 0
            while (isActive) {
                block(i++)
                delay(period)
            }
        }
    }
    The problem with this is that over time the two tasks get way out of sync: A: 47 B: 49 After 50 seconds
    f
    a
    +3
    14 replies · 6 participants
  • m

    Martin Gaens

    07/09/2022, 5:56 PM
    This might be a little off-topic but I decided to give it a shot. I'm using a Kotlin Telegram bot framework from here. Now, the framework allows you to specify callback functions for certain actions. For example, if your Telegram bot receives a message, you can tell the bot to respond to the message. Here's the code:
    fun main() = runBlocking {
        val bot = bot {
            token = "YOUR_API_KEY"
            dispatch {
                text {
                    launch { println("launched") }
                    bot.sendMessage(ChatId.fromId(message.chat.id), text = text)
                }
            }
        }
        bot.startPolling()
    }
    This code should set a callback for when the bot receives any text message from a user. However, the
    launch { }
    never gets launched. And I don't know why! I know all this Telegram bot stuff might be off-topic but it's related to coroutines and I can't comprehend why it wouldn't work. Can somebody tell me what I'm doing wrong?
    e
    j
    +2
    20 replies · 5 participants
  • z

    zak.taccardi

    07/10/2022, 6:49 PM
    Given a
    StateFlow<T>
    instance, I want to log every emission of
    T
    from the source standpoint. Is this possible without duplicating logs for each subscriber?
    d
    s
    +1
    12 replies · 4 participants
  • r

    reactormonk

    07/12/2022, 10:00 AM
    Shouldn't exceptions thrown in a suspend function bubble up like regular exceptions? Trying to catch a lower one, but it's not properly registered, just aborts the program ... err, works.
    b
    n
    23 replies · 3 participants
  • l

    Lukas Lechner

    07/12/2022, 10:59 AM
    Hi! I have a question regarding flows. I want to use something like
    .buffer(capacity = 0, onBufferOverflow = BufferOverflow.DROP_LATEST)
    in my flow, but this doesn't work, since a capacity of
    1
    is used when using
    BufferOverflow.DROP_LATEST
    . What's the use case: The upstream flow items are produced whenever the user clicks a button to perform a network request, which happens downstream after the buffer. When the user presses the button while the network request is on-going, this event should be dropped (that's why I am using a buffer with capacity of 0). However I am not able to achieve this. A new network request is initiated shortly after the previous one is complete when the user clicks the button while the first network request is currently running. Any idea on how to implement this in a nice way?
    s
    n
    5 replies · 3 participants
  • k

    Kulwinder Singh

    07/12/2022, 11:10 AM
    i’m using MutableStateFlow to emit events but while collecting these events i’m adding
    delay
    for 500ms but due to this i’m missing all the other data and only last TempData is recieved
    GlobalScope.launch() {
                flowMain
                    .collect { data ->
                        Log.i("AppLogs", data.toString())
                        delay(1)
                    }
            }
    viewInputLvlArray.forEachIndexed { index, view ->
        flowMain.value = TempData(index, someotherValue)
    }
    l
    m
    +1
    9 replies · 4 participants
  • k

    Kulwinder Singh

    07/12/2022, 11:11 AM
    Actually there are 15 items in array and i want to collect to be called 15 times but with specified delay
  • u

    ursus

    07/13/2022, 12:31 AM
    By default, do I use
    default
    or
    io
    dispatcher? Or rather, when would I want to use io over default? I get that its in the name, but what exactly is io work? Networking? Retrofit has coroutines support, so the thread wont be blocked there. Database? Room has it as well Only thing that comes to mind is file writing/reading? Or would it be bad to just use the
    io
    ? I mean it contracts eventually, right? Can I see how many actual threads are in the
    io
    at some point?
    e
    n
    +2
    56 replies · 5 participants
  • j

    Jakub Gwóźdź

    07/13/2022, 8:28 AM
    Hi. there is something that I’d like to understand: Suppose we have this minimal piece of code:
    suspend fun main() = withContext(MDCContext(mapOf("host" to "local"))) {
        val ktorClient = HttpClient(OkHttp)
        log("entering context")
    
        (1..10).forEach { i ->
            val newContextMap = MDC.getCopyOfContextMap()
            newContextMap["i"] = i.toString()
            withContext(MDCContext(newContextMap)) {
                log("before calling ktor client $i")
                ktorClient.get { url("<https://example.com/$i>") }.bodyAsText()
                log("after calling ktor client $i")
            }
        }
    
        log("exiting context")
        ktorClient.close()
    }
    when run, the MDC is shuffled totally indeterministic:
    10:21:45.238 [main] - entering context {host=local}
    10:21:45.240 [main] - before calling ktor client 1 {host=local, i=1}
    10:21:45.824 [DefaultDispatcher-worker-1] - after calling ktor client 1 {}
    10:21:45.824 [DefaultDispatcher-worker-1] - before calling ktor client 2 {host=local, i=2}
    10:21:45.998 [DefaultDispatcher-worker-1] - after calling ktor client 2 {}
    10:21:45.998 [DefaultDispatcher-worker-1] - before calling ktor client 3 {host=local, i=3}
    10:21:46.102 [DefaultDispatcher-worker-1] - after calling ktor client 3 {host=local}
    10:21:46.103 [DefaultDispatcher-worker-1] - before calling ktor client 4 {host=local, i=4}
    10:21:46.208 [DefaultDispatcher-worker-3] - after calling ktor client 4 {}
    ...
    But as soon as I change first line to
    suspend fun main() = withContext(Dispatchers.Default + MDCContext(mapOf("host" to "local"))) {
    it magically starts working as intended. (same on any other dispatcher, IO or Unconfined) Why is it so? Is it a problem with
    suspend fun main
    , ktor-client, or - most probably - me messing up something here?
    r
    j
    21 replies · 3 participants
  • d

    Dmitry Khalanskiy [JB]

    07/13/2022, 11:14 AM
    📣 📣 📣 kotlinx.coroutines 1.6.4 is here! The highlights: • Module `kotlinx-coroutines-test`: added
    TestScope.backgroundScope
    for launching coroutines that perform work in the background and need to be cancelled at the end of the test. • Fixed the issue with 1.6.2 and 1.6.3 where the updated POM of
    kotlinx-coroutines-debug
    broke some builds.
    ❤️ 11
    :kotlin-intensifies: 7
    👍 2
    👍🏾 1
  • r

    reactormonk

    07/13/2022, 4:57 PM
    I've got a
    suspend fun
    which produces
    ByteArray
    in 16 byte chunks. Reading them is kinda time-intensive, so I was wondering if there's a concept of a lazy channel of bytes, so I say "ready me X bytes" without it reading everything.
    t
    j
    +1
    15 replies · 4 participants
  • m

    Marc Plano-Lesay

    07/14/2022, 1:53 AM
    I have an algorithm that's very easy to run in parallel (think finding a best path), extremely CPU intensive, and would actually benefit from running only n branches at once for n CPU threads (once a solution is found, branches can be culled eagerly, so exploring a solution fully quicker is better than exploring more than n at once). Is there a dispatcher that would block new coroutines until some are finished, in such a way that only n would run for n CPU threads? Or is this too high level for dispatchers and I have to write my own orchestration logic?
    e
    n
    +1
    6 replies · 4 participants
  • r

    reactormonk

    07/14/2022, 8:54 AM
    Are there destructive primitives? I'm looking to write a parser.
    first()
    etc. doesn't advance though 😞 I'd also take a parser-combinator libraries if there's one around 😄
    return channelFlow<TLV> {
            when(input.first()) {
                (0x00.toByte()) -> send(TLVNULL)
                (0x03.toByte()) -> {
                    val length = parseLength(input)
                    val bytes = input.take(length).toList()
                    send(TLVNDEF(NdefMessage(bytes.toByteArray())))
                }
                (0xFD.toByte()) -> {
                    val length = parseLength(input)
                    val bytes = input.take(length)
                    send(TLVProp(bytes.toList().toByteArray()))
                }
                (0xFD.toByte()) -> {
                    send(TLVTerminator)
                    close()
                }
            }
        }
    s
    a
    23 replies · 3 participants
  • m

    Marek Kubiczek

    07/14/2022, 9:07 AM
    I am testing viewModel using the new coroutines testing framework and Mockk library. It seems that the exceptions from child coroutines are swallowed though. It looks more or less like this example:
    @Before
    fun setUp() {
      Dispatchers.setMain(UnconfinedTestDispatcher())
    }
    
    @Test
    fun `Some exemplary test`() = runTest {
        val dependency1 = mockk<Dependency1>()
        val viewModel = TestedViewModel(dependency1)
        viewModel.testedMethod()
        coVerify(exactly = 1) { dependency1.methodToBeCaled() }
    }
    The ViewModel itself is calling that method in viewModelScope
    fun testedMethod() {
      viewModelScope.launch {
        methodToBeCalled()
      }
    }
    However I forgot to mock the called method. I am seeing in log
    Exception in thread "Test worker @coroutine#7" io.mockk.MockKException: no answer found for: Dependency1(#1).methodToBeCalled(continuation {})
    But the test passes. Is it known issue?
    e
    3 replies · 2 participants
  • p

    Peter Kievits

    07/14/2022, 10:02 AM
    A few days I came across an issue with one of our services in a test environment, where we effectively had a deadlock in our coroutine setup. This took a while to track down as nothing showed in the jvm thread dump. Only after inserting lots of log statements and staring at the code was I able to track down the issue. Looking back on this now, it would have been very useful to be able to get some information on the coroutine state out of the running application. Is there any tooling available that would have helped in this instance? Is there something we could do to get thread dump like information of all active and suspended coroutines?
    e
    2 replies · 2 participants
  • r

    reactormonk

    07/14/2022, 1:26 PM
    Does android studio not have the coroutines tab mentioned in https://kotlinlang.org/docs/debug-coroutines-with-idea.html#debug-coroutines ?
    r
    2 replies · 2 participants
  • r

    reactormonk

    07/15/2022, 9:04 AM
    How would y'all register a callback on an element getting passed along in a
    Flow
    (think
    Flow<Card>
    ) - the callback should fire after the card has been disconnected. I'm currently on
    interface Card { var afterCardRemoval: Function<Unit>? }
    and then firing from the scope producing the
    Flow<Card>
    , but that feels kinda dirty.
    j
    r
    +1
    12 replies · 4 participants
Powered by Linen
Title
r

reactormonk

07/15/2022, 9:04 AM
How would y'all register a callback on an element getting passed along in a
Flow
(think
Flow<Card>
) - the callback should fire after the card has been disconnected. I'm currently on
interface Card { var afterCardRemoval: Function<Unit>? }
and then firing from the scope producing the
Flow<Card>
, but that feels kinda dirty.
j

Joffrey

07/15/2022, 9:07 AM
I don't think I understand the question. What does the flow have to do with the question? Are you asking about how to register the callback or how to fire it? For instance, why doesn't
.onEach { afterCardRemoval = { ... } }
work for you?
r

Robert Williams

07/15/2022, 9:08 AM
Are you sure it wouldn't work better as a Flow<Event> where Event can be CardDetected, CardRemoved etc?
r

reactormonk

07/15/2022, 9:09 AM
https://kotlinlang.slack.com/archives/C1CFAFJSK/p1657876089729049?thread_ts=1657875875.988959&amp;cid=C1CFAFJSK That was my first approach as well, but I was wondering if I could associate it by callback instead of the consuming application having to do the association
... how do you even reply to specific replies in slack?
For instance, why doesn't .onEach { afterCardRemoval = { ... } } work for you?
there's basically the
Flow<Event>
which I'm processing, and I'm wondering if I can change the API a bit.
r

Robert Williams

07/15/2022, 9:14 AM
Yeah, unfortunately it's pretty application specific what makes the most sense for your consuming code but I agree callbacks feel a little clumsy when you're already working with coroutines
Another option would be to add a Lifecycle flow inside Card which they could subscribe to separately
r

reactormonk

07/15/2022, 9:16 AM
That's an option, is there one which I can use to send a single value, then finishes?
r

Robert Williams

07/15/2022, 9:26 AM
A StateFlow might work well here because it means if I ever have a Card from anywhere I can always check if the current state is Active or Removed, as well as the original use case of listening for removal
r

reactormonk

07/15/2022, 10:51 AM
I've tried with a
MutableStateFlow
, but there's a) how do I clean it up, aka how do I set the
Flow
from the state to over? Make it a
take()
is my current approach, but I'm not sure I like it. Also, how do I fire off an
async
into the sunset? the
coroutineScope { async { flow.collect { ... } } }
doesn't yield as I'd expect it to.
g

gildor

07/16/2022, 3:10 PM
If you want Flow over just cancel it (or use operators like first()/until() which will close it on some event You cannot cancel MutableStateFlow btw, so it's not probably what you beed
Also flow implementation itself can cancel itself after some event
View count: 21