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
flow
  • c

    christiangruber

    01/08/2020, 11:07 PM
    Hey - I'm having some struggles thinking through flowOn() and the final collect operation. flowOn(SomeDispatcher) seems to configure the up-stream pipeline up to the point where teh pipeline element has a coroutine context already. Cool. But how do I configure
    collect{}
    to run in a particular context? Should I move what was done in a collect() to an onEach{} and then let collect{} just trigger final logging?
    a
    • 2
    • 2
  • a

    Abhishek Bansal

    02/12/2020, 4:38 PM
    Hello, I am trying to concat two flows in a way that I get results sequentially when I collect on it
    flowOf(
     remoteDataSource.getDataFromCache() // suspending function returning Flow<Data>
      .catch { error -> Timber.e(error) },
     remoteDataSource.getDataFromServer() // suspending function returning Flow<Data>
    ).flattenConcat().collect {
    Timber.i("Response Received")
    }
    my expectation here was that I will get first result first and then second after sometime as response comes from server. But the problem here is collect only gets called after server returns result.
    e
    • 2
    • 2
  • a

    Adam Bennett

    03/02/2020, 12:51 PM
    Has anyone cooked up a solution yet for
    publish(selector: (Flow<T> -> Flow<R>)
    ? I’m looking at this issue and I have the exact same use-case https://github.com/Kotlin/kotlinx.coroutines/issues/1086#issuecomment-585174549
    • 1
    • 1
  • a

    Antoine Gagnon

    03/11/2020, 7:23 PM
    Hey all, I’m having some trouble understanding the downside of using buffer() on a flow before collecting it? Is there some reason not to use it? At first I thought it could change the order of values treatment but it doesn’t seem like it
    • 1
    • 1
  • a

    Abhishek Bansal

    03/16/2020, 11:30 AM
    ReceiveChannel#consumeAsFlow() never completes? I wrote a short program to test this
    fun main() = runBlocking<Unit> {
        val test = Test()
    
        launch(<http://Dispatchers.IO|Dispatchers.IO>) {
            println("Receive 1")
            test.getResponseChannel()
                .collect { println("Collect 1 $it") }
        }
    
        launch(<http://Dispatchers.IO|Dispatchers.IO>) {
            println("Receive 2")
            test.getResponseChannel()
                .collect {
                    println("Collect 2 $it")
                }
        }
    
        launch(<http://Dispatchers.IO|Dispatchers.IO>) {
            println("Receive 3")
            test.getResponseChannel()
                .collect {
                    println("Collect 3 $it")
                }
        }
    
        println("Sending A")
        test.responseChannel.send("A")
        println("Sending B")
        test.responseChannel.send("B")
        println("Sending C")
        test.responseChannel.send("C")
    }
    
    class Test {
        val responseChannel = BroadcastChannel<String>(BUFFERED)
    
        fun getResponseChannel(): Flow<String> {
            val channel = responseChannel.openSubscription()
            return channel
                .consumeAsFlow()
                .onCompletion {
                    println("Cancelled")
                    channel.cancel()
                }
        }
    }
    Here you will see that
    onCompletion()
    and hence “Cancelled” never prints. My requirement is to be able to add and detach observers to a broadcast channel. It that achievable?
    d
    • 2
    • 15
  • m

    Maciek

    03/17/2020, 5:51 AM
    Hey guys, I want to send stream of data from one class to the other (adapter/viewholder to activity). Previously I'd use RxJava's Subject for it, what would be recommended way of achieving this with flow? I see how I could do it with channels but it's hard for me to wrap my head around the flow for such use cases
    a
    • 2
    • 3
  • j

    jdiaz

    03/19/2020, 11:08 PM
    I'm starting with flows (and coroutines). I'm trying to create a consumer of a flow that asynchronously executes a function. Would this approach work? https://pastebin.com/k00hWppm I still have some questions like: 1. Should the map of flows and the executor be in the same scope? 2. Would this scale? For example if i publish hundreds of thousands of "events" in the flows, would this become a problem as I'm launching many coroutines? As context this is for a load testing library that I'm playing around with
    • 1
    • 1
  • a

    Ali Sabzevari

    05/15/2020, 6:19 PM
    @Jacob Applin You can add
    "-Xopt-in=kotlinx.coroutines.ExperimentalCoroutinesApi"
    to compiler args. Like this:
    compileKotlin {
        kotlinOptions {
            jvmTarget = "1.8"
            apiVersion = "1.3"
            languageVersion = "1.3"
            freeCompilerArgs = ["-progressive", "-Xopt-in=kotlinx.coroutines.ExperimentalCoroutinesApi"]
        }
    }
    j
    • 2
    • 1
  • f

    fatih

    05/16/2020, 4:53 PM
    Is intermediate flow operators are cancellable? Are they cancelled when the calling scope is cancelled? For instance:
    // If the collecting scope is cancelled before this map operation,
    // seems like map operation is not cancelled and throws an exception
    numbersFlow.map {
        // There is an operation which throws exception
    }
    .flowOn(<http://Dispatchers.IO|Dispatchers.IO>)
    I have to use
    ensureActive()
    before mapping but is it the expected behaviour?
    • 1
    • 2
  • e

    enighma

    05/20/2020, 9:55 PM
    Is there some nifty way to get the last emitted value of a flow, without having to cache it my self?
    v
    a
    • 3
    • 4
  • m

    Marcin Wisniowski

    06/01/2020, 7:20 PM
    Hello, I currently have a
    Channel
    representing a job queue, and a method that `send`s a new job to the queue. A separate coroutine is an infinite
    receive
    loop that processes the jobs. How would I represent that with Flow? I'm not sure how to use the
    flow {}
    builder since I don't know what to
    emit
    upfront, the jobs come from outside.
    f
    • 2
    • 5
  • a

    adk

    06/09/2020, 7:08 AM
    Does anyone have an elegant way to gracefully stop processing a flow, other than cancelling at source? Some sources are not easily cancellable, like (e.g.) StateFlow. I may also have several flows collecting from a StateFlow, but only want to cancel one of them. [Conflated]BroadcastChannel will let me cancel my subscription to it, but there seems no obvious equivalent for flows?
    • 1
    • 1
  • k

    Koya Sivaji

    06/15/2020, 9:27 PM
    I am new to kotlin flows and trying to add Flows to one of my project and facing an issue while converting list of objects of one type to another as shown below. Basically, am not sure which operator to be used for this.
    
    //Repository - method return type is  Flow<List<HistoryEvent>>
    fun getHistoryEvents(): Flow<List<HistoryEvent>>
    
    //ViewModel - calling repository method and trying to convert data to List<AccessoryEvent>
    
    val accessoryEvents : LiveData<List<AccessoryEvent>>=  liveData{
                                                          repository.getHistoryEvents()
    
                                                      // what operator to be used to convert from List<HistoryEvent> to List<AccessoryEvent>
    
                                                            .collect()
                                                          }
    I tried like below
    val eventHistory: LiveData<List<AccessoryEventType>> = 
            liveData {
                deviceRepository.getDeviceEventHistoryFor("abcd")
                    .map { historyEvents ->
                        emit((historyEvents.map { AccessoryEventType.getEventType(it) }))
                    }
                    .collect()
            }
    
    after this, all elements in the returned list are same and equals to the last emitted element. Am not sure what I am doing wrong
    p
    • 2
    • 11
  • m

    Maciek

    07/06/2020, 6:18 PM
    I'm wondering how to structure the code inside the class where I need something like an interval from RxJava, that'll do heavy operation every 50ms. The problem is that I'd want the channel producer to execute heavy operation only when someone is collecting the flow. I don't want to waste resources. Is there some easy way to achieve it?
    Untitled.kt
    g
    • 2
    • 3
  • t

    Tony Blundell

    07/10/2020, 1:12 AM
    Hi, I have a flow of integers. I'd like to keep track of the highest value received and perform an action if a received value is greater than the highest. I'm struggling to figure out which operation I can use to do that https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.flow/ - any ideas? Equivalent without flows might be something like:
    var highest = 0
    for (i in myIntegers) {
       if (i > highest) {
          highest = i
          doSomethingElse()
       }
    }
    e
    • 2
    • 3
  • o

    Oleh Havrysh

    08/11/2020, 3:33 PM
    Hi! Is there something similar to MutableStateFlow, but without “state”? I just want simple entity that allows to pass items from one place and listen for changes at another. So, I don’t need getting last sent item after calling collect(), only new items
    w
    g
    • 3
    • 2
  • m

    miqbaldc

    08/14/2020, 12:47 PM
    @Test
        fun testFlow1() {
            (1..5)
                .asFlow()
                .onEach { println(it) } // prints: 1, 2, 3, 4, 5
        }
    
        @Test
        fun testFlow2() {
            data class Abc(val id: Int)
    
            val list: Flow<List<Abc>> = flow { emit(listOf(Abc(0), Abc(1), Abc(2))) }
            list
                .onEach { println(it) } // prints: list of object instead of each single abc object
        }
    Does currently possible to iterate each index for
    testFlow2
    without using it like this:
    list
       .onEach { 
          it.forEach { abc -> println(abc.id) }
       }
    My goals:
    list
       .onEach { abc -> 
           println(abc.id) // prints: [0, 1, 2]
       }
    • 1
    • 2
  • r

    Ryan Pierce

    08/15/2020, 7:55 PM
    What are the functional differences between a
    SharedFlow
    and a
    StateFlow.buffer(_UNLIMITED_)
    ? Buffering a StateFlow seems to mimic SharedFlow for a simple test I created. Is there a fundamental difference between the way those two flows behave?
    e
    • 2
    • 1
  • c

    Canato

    09/01/2020, 5:45 PM
    Hey people, good day =D I’m having an issue of founding the best usage of Kotlin Flow in a normal API request. Basically I’m doing a small sample Android app with Flow usage for my team. I will retrieve the data from a API endpoint and want to show it in a List. I’m using MVP arch and no LiveData.
    Does any one can guide me to an article or sample app where this works?
    Not sure what is the best single responsibility for this case. • Do I retrieve all information from the Endpoint and emit after each map? • Can I use Flow for pagination ? • Maybe this is not a good case for Flow? Thanks ;)
    r
    • 2
    • 1
  • d

    Dario Pellegrini

    09/03/2020, 7:27 AM
    Yes. Probably that’s the problem. I don’t see any fast solution for solving this with MutableStateFlow. Probably simply MutableStateFlow is not the correct class to use in this case
    w
    • 2
    • 8
  • a

    ansman

    09/04/2020, 7:55 PM
    Is there an equivalent of
    transformLatest
    but for
    combineTransform
    ? I'm looking specifically for something that cancels the work if a new item comes in. For now I can just zip up the items in
    combine
    to a pair and use
    transformLatest
    j
    • 2
    • 1
  • m

    muthuraj

    09/07/2020, 9:00 AM
    I'm using
    StateFlow
    to emit some states and do some work based on that. My code looks like this
    state.onEach(this::handleState)
         .launchIn(scope)
    Now since the
    onEach
    block is a suspending function, if another state is emitted while it is executing, it doesn't cancel the current suspending function. Instead it waits for the
    handleState
    function to finish it's execution and then next state's handling is being done. I realise this is actually done intentionally to handle back pressure and all, but what I want is to cancel
    onEach
    execution when new state is received and run
    onEach
    for the new state. Currently I'm running the
    handleState
    block in another coroutine using
    scope.launch { }
    , store that job as member variable, then cancel that in
    onEach
    before launching new coroutine. Is there any other way to achieve this?
    w
    • 2
    • 2
  • m

    Matti MK

    09/07/2020, 12:02 PM
    Hey! I’m new with flow and I’ve been pondering how to implement the following data flow. My use case is that I’m using TMDB API with two endpoints: one to fetch a list of genres and second to fetch a list of movies per genre. This means that if the API returns N genres I have to make N requests to fetch the list of movies. My repository returns a flow of these objects, for example Flow<List<Genre> and Flow<List<Movie>>. My question is, what would be a flow way of “combining” these two streams, so that once the genres stream emits a value (it will only emit one value, all the genres), the genres would be looped over and movies would be queried for each, then those two combined. If I were to do this without flow I’d do something like:
    fun fetchData() {
       val genresWithMovies: List<GenreWithMovies> = dataSource.queryGenres().map { genre ->
            val movies = dataSource2.queryMovies(genre.id)
            genre.movies = movies
            genre
       }
    }
    Any tips?
    d
    • 2
    • 2
  • r

    Ryan Pierce

    09/08/2020, 3:42 AM
    If you have a buffered SharedFlow with a slow and fast collector, and the fast collector finishes collecting the most recent value, does the fast collector suspend until the slow collector finishes collecting that same most recent value? Or does the fast collector pull the next value from the buffer and get ahead of the slow collector? If the latter, is the total buffer space (replay + extraBuffer) equal to the amount of values a fast collector can get ahead of a slow collector?
    e
    • 2
    • 2
  • d

    Daniele B

    09/14/2020, 9:37 PM
    The shared model I am working on (in
    commonMain
    ) looks like this:
    class CoreViewModel {
        internal val mutableStateFlow = MutableStateFlow(AppState())
        val stateFlow: StateFlow<AppState>
            get() = mutableStateFlow
    }
    Can anyone show how it’s possible to collect the
    StateFlow
    value in Swift, on the iosApp side? I am looking for a way to connect the StateFlow value to an ObservableObject.
    • 1
    • 1
  • c

    Christian S.

    09/18/2020, 7:16 PM
    Hello everyone, I am a Kotlin newbie and are looking for a way to resume a Flow after an exception has been thrown by the emitter. I want to adhere to Exception Transparency. I have seen a workaround on SO (https://stackoverflow.com/a/63886110) but wanted to ask if you know an easier / less custom solution. Thanks!
    g
    • 2
    • 6
  • m

    Marc Knaup

    10/04/2020, 5:26 PM
    Is there an example how to implement rate limiting with Flow? I have an API client that is supposed to make hundreds of requests. X requests should run in parallel and as soon as one of the request receives a rate limiting error from the server, all request processing should pause until the waiting period is over.
    g
    • 2
    • 1
  • t

    Trym Nilsen

    10/05/2020, 4:09 PM
    Is it possible to create a flow operator similar to
    collect
    with its own coroutine scope for each item it receives? E.g lets say I have an updating list of bicycles, a
    Flow<List<Bicycle>>
    . For each bicycle I can request a price, unfortunately this API requires me to request the prices for a single bicycle at a time. This is all fine i can spin up some requests using a couple of
    async
    builders, no problem so far. The API for requesting prices might be slow at times, slower than the stream of new bicycles that becomes available or taken. This however creates the issue of still be working on fetching prices for bikes that are no longer available or taken. Is there any way to create a coroutine scope for each item collected from my
    Flow<List<Bicycle>>
    and then cancel it when a new item is collected, If I understand correctly due to the sequential nature of flows, the next item is not requested until the previous is finished/completed?
    w
    • 2
    • 2
  • a

    Alex

    10/13/2020, 9:53 AM
    Hey is there a non-state version of
    MutableStateFlow
    ? I have been using
    ConflatedBroadcastChannel
    , but would like to move to flow completely. I know there is
    Flow
    itself, but I have not found a way to send values to it from outside the creation lambda.
    k
    m
    g
    • 4
    • 25
  • m

    Marc Knaup

    10/13/2020, 9:47 PM
    Why does
    stateIn
    need an initial value? I keep writing
    .stateIn(…, …, initialValue = null).filterNotNull()
    e
    g
    • 3
    • 14
Powered by Linen
Title
m

Marc Knaup

10/13/2020, 9:47 PM
Why does
stateIn
need an initial value? I keep writing
.stateIn(…, …, initialValue = null).filterNotNull()
e

ephemient

10/13/2020, 9:55 PM
what would
StateFlow.value
return without an initial value?
m

Marc Knaup

10/13/2020, 9:59 PM
Good point. I don’t care about that property but it’s there. I’ve always wondered why it isn’t a
suspend fun value()
instead.
e

ephemient

10/13/2020, 10:00 PM
https://youtrack.jetbrains.com/issue/KT-15555
g

gildor

10/13/2020, 11:19 PM
Because state flow was designed for use cases, where default value is useful, such as UI state Also suspend value() is the same as existing suspend first()
m

Marc Knaup

10/14/2020, 12:41 AM
So it was designed for a subset of potential use cases 😉 Anyway, I don’t think it will be changed anymore. So I have to work around it or make my own operator.
e

ephemient

10/14/2020, 12:51 AM
perhaps SharedFlow/.shareIn() would be a better fit for you
m

Marc Knaup

10/14/2020, 1:21 AM
I think I’d then have to add
.conflate().distinctUntilChanged()
before each
.shareIn
to achieve the same behavior.
So at the end both approaches are quite repetitive.
g

gildor

10/14/2020, 1:52 AM
But MutableSharedFlow doing the same waht you need, isn’t it?
it doesn’t have any default value, you can control how buffere works on overfloiw
So it was designed for a subset of potential use cases
Exactly. as any other abstraction I believe, has some use cases in mind
Looks that this what you need
MutableSharedFlow(replay = 1, onBufferOverflow = BufferOverflow.DROP_OLDEST)
But yeah, you still need distinctUntilChanged if you want behaviour of StateFlow
anyway, I don’t think you need something custom, just a combination of a couple existing operators
View count: 2