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

    alex

    08/26/2021, 6:21 PM
    We have an argument in our team, regarding cache coherency and how coroutine context switch affect it. Imagine the situation: 1. Coroutine C modifies object O 2. Coroutine C yelds, thread is switching to another coroutine 3. Coroutine C is resumed by another thread, uses data from O and updates object O again 4. Process repeats, context switching is happening a lot, and usually under few milliseconds Note: there is no concurrent access to object O, only a single coroutine works with O at any point in time Is there a chance that updates made by one of the threads in iteration N are not visible by another thread on iteration N+1? In other words, what happens with CPU cache when coroutines are switched way too fast? Is it coherent no matter what?
    e
    c
    +2
    • 5
    • 19
  • p

    Patrick Ramsey

    08/27/2021, 3:31 AM
    was just poking around in kotlinx-coroutines. Saw
    /**
     * Returns the context of the current coroutine.
     */
    @SinceKotlin("1.3")
    @Suppress("WRONG_MODIFIER_TARGET")
    @InlineOnly
    public suspend inline val coroutineContext: CoroutineContext
        get() {
            throw NotImplementedError("Implemented as intrinsic")
        }
    That is a wild bit of code. How does a
    suspend inline val
    exist in the language, and how is it that all it takes to make it work is to suppress the compiler warning that that’s not allowed?
    e
    • 2
    • 1
  • f

    frankelot

    08/27/2021, 7:50 AM
    I'm trying to understand coroutine internals by watching this

    excelent video▾

    by Roman Elizarov. Unfortunately, There's something that doesn't add up for me. According to the slides, each
    suspending
    function is transformed into a regular function that takes an additional parameter
    Continuation<OriginalReturnType>
    ... (emphasis in
    OriginalReturnType
    ) But then in the second screenshot, the same
    Continuation
    seems to be used to call multiple suspending functions which different return types (
    requestToken
    and
    createPost
    ) I would think
    suspend fun requestToken
    is transformed to
    requestToken(Continuation<Token>)
    and that
    suspend fun createPost
    should be
    createPost(Continution<Post>)
    right? So how come we can pass
    sm
    into both?
    l
    r
    +3
    • 6
    • 35
  • g

    Greg Hibberd

    08/27/2021, 2:20 PM
    Is there a better way of handling exceptions within default values without manually creating loads of overloading methods?
    fun getDefault(): Any {
        check(false) { "failed"}
        TODO()
    }
    
    fun method(param: Any = getDefault()) = flow<Any> {
        TODO()
    }
    i.e avoiding loads of these when you have 2+ default values:
    fun method() = flow {
        method(getDefault())
            .collect {
                emit(it)
            }       
    }
    c
    • 2
    • 3
  • s

    Scott Whitman

    08/28/2021, 1:26 PM
    Map used on a SharedFlow returns a Flow. Is there an equivalent function to map that will return a SharedFlow?
    l
    • 2
    • 8
  • a

    Ayfri

    08/29/2021, 9:00 AM
    Hi, if I have a suspend function where inside I execute a function which requires a lambda not suspend (I'm using a Java library), but I want to execute lambda things inside Do I have to add
    runBlocking { //code }
    everytime or is there a way to intercept the upper suspend ?
    u
    z
    • 3
    • 2
  • h

    Hans Ellegard

    08/29/2021, 5:00 PM
    I'd like to wrap a blocking call so that it can be used in a cancellable coroutine, i.e. add preemption. Clearly this is going against the grain, as the whole point of coroutines and their cancellation is cooperation, but still, I'd like to wrap this blocking interface once and for all so that it can be used without fear within coroutines. I have looked at https://alexsaveau.dev/blog/kotlin/android/advanced-kotlin-coroutines-tips-and-tricks and https://discuss.kotlinlang.org/t/coroutines-and-cancelling-blocking-code/12165, but I can't get my code to work. Here's some code exhibiting the issue (perhaps needless to say, this is simplified example code and not my production code, but the issue's the same) :
    // You are not allowed to change this class.
    class Foo : AutoCloseable {
        private val outstream = PipedOutputStream()
        private val instream = PipedInputStream(outstream)
    
        override fun close() {
            instream.close()
        }
    
        fun blockingCall() {
            instream.read() // blocks the thread until e.g. the stream is closed
        }
    }
    
    /**
     * Wraps the AutoCloseable usage so that the AutoCloseable is closed when the coroutine is cancelled.
     */
    suspend fun <T: AutoCloseable> closeOnCancel(block: (T) -> Unit) {
        // How do I implement this function?
        // I have tried using suspendCancellableCoroutine, but I think I misunderstood that function.
    }
    
    fun cancelBlockingCall() {
        val foo = Foo()
        runBlocking(<http://Dispatchers.IO|Dispatchers.IO>) {
            withTimeout(100) {
                foo.closeOnCancel { it.blockingCall() }
            }
            println("Yay, arriving here means problem solved")
        }
    }
    Could I get some help or pointers to documentation regarding how to implement
    closeOnCancel
    in general?
    b
    j
    • 3
    • 6
  • f

    frankelot

    08/29/2021, 9:11 PM
    Hi! maybe someone here can help me, I’ve read this article Coroutine Context and Scope by Roman Elizarov a thousand times and I still don’t get why we need a
    CoroutineScope
    interface. I get that coroutines builders like
    launch
    are extension functions on that class, but why can’t they just be extension function on
    CoroutineContext
    instead?
    j
    s
    • 3
    • 5
  • j

    Jan Groen

    08/29/2021, 9:19 PM
    Hey o/ I'm trying to implement the coroutines library on a JVM-based gaming platform. I was wondering if there is a possibilty to implement the
    Dispatchers.Main
    dispatcher (other than using the
    ServiceLoader
    ). This would be useful, because a lot of the data needs to be updated from the main game loop. I'm aware that I could create my own dispatcher and I have done that. I just think that it would be more ideomatic if I could use the
    Dispatchers.Main
    Dispatcher.
    a
    e
    e
    • 4
    • 6
  • l

    Lilly

    08/30/2021, 5:08 PM
    Given this simple method which is triggered on button click in Compose:
    // In ViewModel
        fun toggleScan() {
            when {
                isScanning.value -> stopScan()
                else -> {
                    startScan()
                    presenterScope.launch(Dispatchers.Default) {
                        delay(DISCOVERY_TIMEOUT)
                    }
                }
            }
        }
    What is an elegant way to avoid creating a new coroutine on every button click?
    z
    a
    +2
    • 5
    • 14
  • j

    j0bro

    09/01/2021, 9:52 AM
    Hey people! Dropping a bit of a bomb question here: is there already effort underway to create an
    LinuxArm32Hfp
    version of coroutines?
    t
    • 2
    • 1
  • а

    Андрей Коровин

    09/01/2021, 6:29 PM
    Hi, I have faced a problem with hot flows while unit testing. I saw people had similar problems but not in the exact way, so it would be nice if someone could explain the following behaviour: 1. This test fails with
    java.lang.IllegalStateException: This job has not completed yet
    @Test
    fun testHotFlow() = coroutinesTestRule.testDispatcher.runBlockingTest {
        val eventChannel = Channel<String>()
        val events = eventChannel.receiveAsFlow()
    
        val event = events.first()
        assertEquals(event, null)
    }
    2. This test doesn’t fail
    @Test
    fun testHotFlow() = coroutinesTestRule.testDispatcher.runBlockingTest {
        val eventChannel = Channel<String>()
        val events = eventChannel.receiveAsFlow()
    
        launch {
            eventChannel.send("First element")
        }
    
        val event = events.first()
        assertNotNull(event)
    }
    e
    • 2
    • 18
  • c

    Colton Idle

    09/02/2021, 4:32 AM
    Stumbled upon this today when trying out firebase for the first time. https://github.com/Kotlin/kotlinx.coroutines/tree/master/integration/kotlinx-coroutines-play-services Why does kotlin have google play services intergration? Vs the opposite (play services having coroutine support)? Mostly curious if this is something I could seriously adopt or if its just experimental from kotlin team.
    o
    • 2
    • 6
  • p

    Patrick Ramsey

    09/02/2021, 6:40 AM
    So, I’m testing a method that uses both
    suspendCancellableCoroutine {}
    and
    withTimeout {}
    , and I’m running that test using a TestCoroutineDispatcher. In particular, I’m testing that the timeout fires if
    cont.resume()
    is never called within
    suspendCancellableCoroutine {}
    . My test runs the code in question inside a <test coroutine dispatcher>.runBlockingTest {} block. What I’m finding is that sometimes, the test passes as expected. But other times (it really feels nondeterministic and timing-related --- it changes depending on which tests are called before it, and whether or not it’s called in a debugger), instead of hitting the timeout, the internal call to
    dispatcher.advanceUntilIdle()
    leaves the test dispatcher idle but the coroutine still running, resulting in an IllegalStateException.
    • 1
    • 12
  • f

    Florian

    09/02/2021, 10:04 AM
    getLongestCompletedStreak
    can take a while if the List is large. Will this setup do the list calculation on a background thread?
    private val taskStreaksMax =
            allTasksWithTaskStatisticsFlow.map { allTasksWithTaskStatistics ->
                allTasksWithTaskStatistics.map { taskWithTaskStatistics ->
                    TaskStreak(
                        taskWithTaskStatistics.task.id,
                        taskWithTaskStatistics.taskStatistics.getLongestCompletedStreak()
                    )
                }
            }.flowOn(defaultDispatcher)
    o
    • 2
    • 7
  • o

    Orhan Tozan

    09/02/2021, 10:40 AM
    Any reason why it still won't compile? I added the coroutines test library as a dependency in my KMP project:
    val jvmTest by getting {
        dependencies {
            implementation("org.jetbrains.kotlinx:kotlinx-coroutines-core-test:1.5.2")
        }
    }
    j
    • 2
    • 14
  • v

    Vsevolod Tolstopyatov [JB]

    09/02/2021, 11:31 AM
    📣 📣 📣 
    kotlinx.coroutines
     1.5.2 is here! • Kotlin 1.5.30 with new K/N Apple Silicon targets • JS bug fixes: proper
    Dispatchers.Default
    on React Native, proper
    onUndeliveredElement
    for JS Channels • Various
    Mutex
    optimizations Full changelog: https://github.com/Kotlin/kotlinx.coroutines/releases/tag/1.5.2
    🎉 17
    j
    • 2
    • 3
  • f

    Florian

    09/02/2021, 12:42 PM
    I get that I should not hardcode dispatchers in my repos, viewmodels, etc. But what if I want to switch Dispatcher in an extension function of some data class?
    suspend fun List<TaskStatistic>.getCurrentCompletedStreak(): Int =
        withContext(Dispatchers.Default) {
            var currentStreak = 0
            for (statistic in this@getCurrentCompletedStreak.reversed()) {
                if (!statistic.taskCompleted) break
                currentStreak++
            }
            currentStreak
        }
    r
    d
    e
    • 4
    • 11
  • n

    nilTheDev

    09/03/2021, 12:22 PM
    This is a talk Roman Elizarov gave back in 2017 that explains coroutine's internals. In this particular snippet, apparently, that
    await
    extension function is wrapping the inherently blocking call inside it to make it work with coroutines. As far as my understanding goes the
    enqueue
    method submit the call into some kind of thread pool that waits in the queue until executed. Question 1: If I throw
    100_000
    requests asynchronously what would be the mechanisms that would prevent the program from being crashed? Would that only be the queue that the
    enqueue
    method submit to? Or there are some other mechanisms that
    suspendCoroutine
    provides? Question 2: What exactly is the role that
    suspendCoroutine
    plays here? Since the extension function
    Call<T>.await()
    is a suspending function why can't it just use the continuation that this function would receive to write the callback? There must be some extra functionality that
    suspendCoroutine
    provides other than access to the continuation. What exactly is that?
    z
    e
    g
    • 4
    • 9
  • m

    maxmello

    09/03/2021, 12:59 PM
    Hey, this is an Android + Coroutine question, but it would technically apply to all programs that have some global state, so I decided to ask it here: In my classes that are effectively singletons, which are the classes of which I create one instance inside my
    Application
    class and always reference them via the
    Application
    instance, does it make any difference if I use
    GlobalScope.launch
    to launch a coroutine, or let my
    Application
    extend
    CoroutineScope
    and pass in the
    Application
    instance to the class to do
    application.launch
    instead? I ask because of the (new?) warnings about
    DelicateCoroutinesApi
    when using GlobalScope. When I use the second approach, the warning goes away, but I would assume they are functionally the same as both the Application’s coroutineScope and GlobalScope live the whole time the app is running? (Note this is mostly about doing things once asynchronously on start of the application)
    l
    z
    • 3
    • 3
  • d

    Didier Villevalois

    09/03/2021, 4:30 PM
    Hi all. I need guidance with coroutines and cancellation. I need to maintain a concurrent map of jobs indexed by strings. I need to be able to manually cancel the a job from its key but also remove the job when cancelled because of a failure or normal completion. For now, I am doing the following, but is there a better idiom?
    private class JobMap<K> {
        private val jobs = atomic(mapOf<K, Job>())
    
        fun add(key: K, factory: () -> Job) {
            jobs.update {
                val job = factory()
                job.invokeOnCompletion { cause ->
                    if (cause == null || cause !is CancellationException) jobs.update { it - key }
                }
                it + (key to job)
            }
        }
    
        fun remove(key: K) {
            jobs.getAndUpdate { it - key }[key]?.cancel()
        }
    }
    e
    • 2
    • 5
  • k

    Krzysiek Zgondek

    09/03/2021, 8:25 PM
    Is there any way to get child's coroutineContext elements of a scope job? ie. lets say i have a scope:
    scope: CoroutineScope
    and i have launched a job in that scope:
    val context = Dispatchers.Default + CoroutineActionId(id)
    val newJob= scope.launch(context) { ... }
    given that
    CoroutineActionId(id)
    is an
    AbstractCoroutineContextElement
    how can i reach it having only
    scope
    ? I've tried like this:
    val children = scope.coroutineContext[Job]?.children
    val activeAction = children?.firstOrNull { it[CoroutineActionId]?.id == id }
    if (activeAction != null) {
        activeAction.cancelChildren()
        activeAction.join()
    }
    but after debugging i've realized that children of scope's
    Job
    are different than jobs refs returned from
    launch
    but the amount is correct
    . It looks like i see actual job on scope's
    val children = scope.coroutineContext[Job]?.children
    list but when i try to get
    CoroutineActionId
    like this
    children?.forEach {
         println("#state: caid = "  + it[CoroutineActionId]?.id)
    }
    it doesn't exist
    z
    • 2
    • 4
  • j

    Jorge Castillo

    09/04/2021, 10:52 AM
    Hi! I know
    Channel
    does this, but I'm trying to manually write a
    Queue
    that suspends when enqueing an element and the queue is full, and also suspends when dequeing and the queue is empty
    class Queue<T>(private val limit: Int = 5) {
    
      private val elements: MutableList<T> = mutableListOf()
    
      suspend fun enqueue(t: T): Unit = suspendCancellableCoroutine { cont ->
        var enqueued = false
        while (!enqueued) {
          if (elements.size < limit) {
            elements.add(t)
            enqueued = true
            cont.resume(Unit)
          }
        }
      }
    
      suspend fun dequeue(): T = suspendCancellableCoroutine { cont ->
        var dequeued = false
        while (!dequeued) {
          if (elements.isNotEmpty()) {
            val element = elements.first()
            elements.remove(element)
            dequeued = true
            cont.resume(element)
          }
        }
      }
    }
    Adding a question about how to test this in a thread.
    u
    z
    • 3
    • 16
  • e

    Erik Dreyer

    09/04/2021, 8:42 PM
    I found the following article and wondered what the Kotlin version might look like: https://dzone.com/articles/print-even-and-odd-numbers-using-two-threads-compl My solution: https://gist.github.com/edreyer/e3ac7fbdd6146806b3839d79262f63bd I’m still rather new to Kotlin, so not sure if this is the best. Would love comment on the gist if there is a better way
    s
    s
    • 3
    • 3
  • j

    João Rodrigues

    09/04/2021, 11:31 PM
    Hi! I've been having some trouble wrapping my head around how coroutines work with non-suspending code. For example, I was trying to do some load testing, by emitting a ton of Kafka events and since I was learning about coroutines, I wanted to give it a try. I used the "normal"
    KafkaProducer
    , and it's
    send
    method (non-suspending, native java function). If I understood correctly, the coroutines for this purpose should be in the
    <http://Dispatchers.IO|Dispatchers.IO>
    context, correct? Can the number of emitting coroutines exceed the number of threads of my machine, given that the send function is non-suspending?
    j
    • 2
    • 3
  • c

    Colton Idle

    09/05/2021, 8:01 PM
    How would I go about updating this code to be synchronous in retrieving that first value?
    val loggedIn: Flow<Boolean> = prefs.data
        .map { preferences ->
            preferences[authenticated] ?: false
        }
    This is my first time working with Flow, so I might be misunderstanding it's usage, but my use case is that when my app starts, I'm reading from
    prefs
    and I need to know (at the moment the app starts) whether I'm logged in or logged out, but then every time after the first time, I want it to be async. Is there some typical pattern for when you want a flow... BUT you want to have the actual first item in the Flow before you go any further?
    j
    u
    o
    • 4
    • 12
  • u

    uli

    09/05/2021, 8:37 PM
    Would
    prefs.data.onStart{ emit (initialPrefs) }
    do the job? https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.flow/on-start.html
    c
    • 2
    • 2
  • l

    Lilly

    09/06/2021, 11:32 AM
    Is there some flow operator to make this less verbose?:
    val response = readPacketFlow().first { response -> response is Acknowledgement }
    when (response) {
    	Acknowledgement -> true
    	else -> false
    }
    Edit: I would like to return true or false from flow if the first item matches a given predicate.
    o
    t
    • 3
    • 5
  • e

    eirikb

    09/06/2021, 7:46 PM
    Hi. I'm trying to display log messages in a view using a Flow. Log messages are streamed over the network, I can't query them, only receive them one by one. I want to cache a given amount of messages in-memory, say 10 000, but only show the last N messages in the view (based on user options). I thought Flow would be great since the view would not consume the flow when not open, and when open user options such as filtering could be applied, and new messages would end up in the view.
    s
    • 2
    • 4
  • t

    Tower Guidev2

    09/07/2021, 7:34 AM
    Hi, I am investigating Kotlin Flows (On Android with Room/Sqlite DB)
    j
    • 2
    • 3
Powered by Linen
Title
t

Tower Guidev2

09/07/2021, 7:34 AM
Hi, I am investigating Kotlin Flows (On Android with Room/Sqlite DB)
I have a requirement where I need to consume a
Flow
Once then "disable" it. I have a Room database table where I have status values per "Action". The status can be
SUCCESS
,
EMPTY
,
FAILURE
each status row has an
ARCHIVED
column that is either true or false. The DB table resembles this
data class OutcomeDO(
    @ColumnInfo(name = "name") val name: String,
    @ColumnInfo(name = "outcome") val outcome: Outcome,
    @ColumnInfo(name = "archived") val archived: Boolean = false,
) {
    @PrimaryKey(autoGenerate = true)
    @ColumnInfo(name = "result_local_id")
    var resultLocalId: Long = 0L
}
My DAO resembles this
@Query("SELECT * from result_table WHERE name = :name AND archived = :archive")
fun fetch(name: String, archive : Boolean = false): Flow<OutcomeDO>
I query this table like this:-
return database.outcomeDAO().fetch(name = Fred::class.java.name).filterNotNull().flatMapLatest { flowOf(it.outcome) }
and consume the Flow like this:-
outcome.take(1).collect { outcome ->
    when (outcome) {
        Success -> // display data
        Empty -> {
            showError(anchorView, R.string.no_data_found)
        }
        Failure -> {
            showError(anchorView, R.string.data_search_failed)
        }
    }
}
Once the flow has been consumed in the above snippet I wish to set that particular row on the underlying database to
ARCHIVED
= true How can I achieve this? Is there a Flow operator such as OnCompletion/OnConsumed that I can employ to detect when the flow has been consumed and allow me to update a specific row on my DB table?
or how can I tell when a Flow has already been collected?
j

Joffrey

09/08/2021, 6:46 AM
There is indeed
onCompletion
that you can add when you create the flow to detect the end of the collection (normally or exceptionally)
View count: 5