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

    Ansh Tyagi

    11/09/2021, 7:31 PM
    Hey Everyone! so is I am getting started with multiprocessing and wanted to know if there is something similar to pythons Pool.map() in kotlin? Or an example showing how can we make a process pool and then run an iterable callback in it.
    b
    c
    +2
    • 5
    • 10
  • d

    Diego

    11/17/2021, 4:05 PM
    Guys imagine I have these two sources of data:
    val flowA: Flow<String>
    suspend fun funB(): Int
    How can I combine the result of both into a Flow?
    n
    • 2
    • 3
  • m

    miqbaldc

    11/22/2021, 6:41 AM
    Does
    .collect
    -in flows inside
    .collect
    works this ways?
    Would love to know if there’s any suggestion/feedback to improve below snippet code ❤️
    lifecycleScope.launchWhenCreated {
            val uploadsBody = mutableListOf<File>()
            files
                .asFlow()
                .map { originalFile ->
                    originalFile
                        .compressImageAsFlow(this)
                        .collect { compressedImageFile ->
                            uploadsBody.add(compressedImageFile)
                        }
                    uploads
                }
                .collect { result ->
                    viewModel.uploadFile(this, result)
                }
    }
    b
    n
    • 3
    • 6
  • j

    joadar

    11/22/2021, 5:56 PM
    Hello guys 🙂 I try to update the data into a Flow, but I have this (working) solution:
    private val _uiState = MutableStateFlow(DeveloperUiState(isLoading = true, sectionsItems = DeveloperSections()))
    val uiState: StateFlow<DeveloperUiState> = _uiState.asStateFlow()
    
    ...
    
    _uiState.update {
        it.copy(
            sectionsItems = it.sectionsItems.copy(
                userSection = it.sectionsItems.userSection?.copy(
                    options = it.sectionsItems.userSection.options.copy(
                        userPremium = it.sectionsItems.userSection.options.userPremium.copy(
                            isSelected = isChecked,
                            summary = if (isChecked) "Yes" else "No"
                        )
                    )
                )
            )
        )
    }
    Is there a way to reduce this path to edit a specific variable from an object? Thanks for your inputs!
    n
    • 2
    • 5
  • c

    Chris Fillmore

    11/25/2021, 2:35 PM
    Is there an existing Flow method like this? I don’t see one, just curious if I’m missing it.
    fun <T> Flow<T>.onChange(action: (oldValue: T, newValue: T) -> Unit): Flow<T>
    w
    e
    • 3
    • 7
  • r

    rachael

    11/30/2021, 5:42 PM
    New to Flow and I'm wondering if anyone can point me towards some resources for a particular use case. I want a Repository that holds a List<Message>. These messages are fetched from a backend service via GET request, but can also be updated at any time by events that come in from a pub/sub service. Currently the result from the backend is a MutableLiveData, but increasingly we're seeing ConcurrentModificationExceptions because we need to read and potentially do some processing on the list while events are coming in and updating the list. It seems like Flow's streams of data might help here but it would be nice to look at some concrete examples.
    c
    • 2
    • 5
  • j

    joadar

    11/30/2021, 9:01 PM
    Hello, is it possible to call a collect in a collect? I have this code:
    dateFlow.collectLatest { date ->
        repository.getContentFromDate(date).collect { result ->
    I can change the date so the content update. But I have a favorite feature on the content. On the default date, the favorite is working well (I collect the new value) but when I update the date, the collect doesn’t work on favorite events. What am I doing wrong? Thanks.
    e
    • 2
    • 5
  • e

    expensivebelly

    12/01/2021, 9:51 AM
    Quick question:
    suspend fun waitForNetworkConnection() = isConnectedFlow.filter { it }.single()
    isConnectedFlow
    is a StateFlow, initially
    false
    (let’s assume we are in airplane mode in an Android app), then network connection is back,
    isConnectedFlow.value = true
    , however, the
    waitForNetworkConnection
    never ends and I don’t know why, I can see it only enters in the
    filter
    once and the second emission is ignored? I’ve also tried
    isConnectedFlow.first { it }
    to no avail. Any help would be appreciated
    b
    • 2
    • 6
  • s

    Simon Lin

    12/03/2021, 2:36 AM
    I have a SharedFlow to emit user data to UI layer like below, and the user can click a button to call
    refresh()
    to update
    userFlow
    (let
    emit(userRepository.getUser())
    call again.) How do I implement
    refresh()
    ?
    // ViewModel
    
    val userFlow = flow {
        emit(userRepository.getUser())
    }.shareIn(viewModelScope, SharingStarted.WhileSubscribed(), replay = 1)
    
    fun refresh() {
        // How to reload user?
    }
    n
    • 2
    • 1
  • m

    Mikael Alfredsson

    12/09/2021, 7:26 AM
    Is there any kind of flow that mixes state and shared flow? I would like to have a flow that emits every time a new value (even if the value is equal to the last value) but has a
    .value
    parameter so that I can query the parameter at any point in time? (sort of a stateful share flow 🙂 )
    e
    n
    • 3
    • 8
  • v

    Václav Škorpil

    12/12/2021, 7:44 PM
    Hi, as far as i know using suspend in function that returns flow is bad practice and you should use CoroutineContext.() insted. But what to do when it is a member function and you need to call suspend fun inside? This is how i would call it with suspend
    class KeywordService(val keywordRepo: KeywordRepo) {
    
        fun getKeywordData(
            keywordId: UUID,
        ): Flow<String> {
            val name = keywordRepo.getKeywordName() // suspend function 
            return keywordRepo.getKeywordData(name) // function that returns flow
        }
    }
    Currently i am calling it with a flow builder, but i am not sure if this is correct.
    class KeywordService(val keywordRepo: KeywordRepo) {
    
        fun getKeywordData(
            keywordId: UUID,
        ): Flow<String> = flow {
            val name = keywordRepo.getKeywordName() // suspend function 
            val dataFlow = keywordRepo.getKeywordData(name) // function that returns flow
            emitAll(dataFlow)
        }
    }
    This way it feels little bit clunky, is there any better way to do it?
    f
    • 2
    • 12
  • s

    Stylianos Gakis

    12/13/2021, 8:56 AM
    Got a question regarding collecting a flow inside the scope of mapping some other flow, and I am a bit confused if I could improve the way I am currently approaching this. I have a use case where: I have a stateFlow that holds a Result type of an UUID. With that UUID I am starting a new subscription (a flow) that also returns a result type. Finally with this latest result, if it’s successful, I need to perform another API call to get the final data which I am interested combining the original stateflow data with And all this should at the end maps to the UI state of type ViewState More in thread: 🧵
    n
    • 2
    • 5
  • s

    Stylianos Gakis

    12/17/2021, 11:52 AM
    I am collecting a flow, and inside the scope of that collect function I would like to perform 2 network requests in parallel that can start independently, and simply want the result of both in the end. Inside the scope of
    .collectLatest { //here }
    I am not under a coroutine scope, but simply a suspend function, therefore I do not have access to
    CoroutineScope.async
    . I should be able to do this somehow right? ps. I’m using collectLatest with the idea that if a new value comes, the two async calls I am doing should cancel themselves since I will not be needing their result anymore, is this a correct assumption?
    w
    • 2
    • 6
  • j

    John Aoussou

    12/17/2021, 3:04 PM
    I'd like to know the simplest way to make a StateFlow directly depend on another. For example, let's say in my viewmodel I have:
    private val _stateFlow1 = MutableStateFlow(0)
    Is there a way to define
    _stateFlow2
    so that
    _stateFlow2.value = _stateFlow1.value * _stateFlow1.value
    ?
    s
    • 2
    • 6
  • d

    darkmoon_uk

    12/21/2021, 3:11 PM
    Is there no
    flatMap-
    family operator that ignores new upstream emissions while a mapping operation is being processed (i.e. mapped stream is not completed)? How could this be achieved? I don't want emissions buffered as with
    concat
    , but thrown away/ignored.
    n
    • 2
    • 4
  • e

    elye

    12/22/2021, 4:57 AM
    Hi, I have a question We can create LiveData or StateFlow in a similar way as below
    val _liveData = MutableLiveData(0)
    val _stateFlow = MutableStateFlow(0)
    But In LiveData, we can ensure the data is saved and restored by using
    val _liveData: MutableLiveData<Int> = savedStateHandle.getLiveData("Key", 0)
    For StateFlow, is there a way (or API) to keep the last value and restore it, like what we have in LiveData?
    👆 1
    j
    • 2
    • 1
  • m

    Maciek

    12/22/2021, 11:50 AM
    I'm having troubles understanding the exception handling in the flow. Could someone explain why the throwable completes the flow even with the
    catch { }
    in the chain? If I'd want to have a infinite flow I must handle the exceptions with
    try catch
    in the lambdas because flow will close after any exception "leaking" to the stream, right? Or is there a way to do some explicit recover from the exception? Example code, only
    0
    will be emitted, next emit
    1
    is lost due to flow completion after exception.
    flow {
      emit(0)
      emit(1) // this emit is never reached
    }
      .onEach { if (it == 0) throw Throwable() }
      .catch { println(it) }
      .collect()
    e
    n
    e
    • 4
    • 9
  • f

    Florian Walther (live streaming)

    01/01/2022, 10:50 AM
    Did anyone try using
    getOrAwayValue()
    (the helper function from Google's testing samples) on
    Flow#asLiveData()
    ? I'm not getting a value.
    g
    • 2
    • 13
  • s

    Stylianos Gakis

    01/04/2022, 9:45 AM
    Is there a nice way to trigger a restart of a flow that is turned into a StateFlow using
    statein
    ? I’ll show you my use case and try to explain what I mean in the thread 🧵
    w
    e
    • 3
    • 13
  • s

    Slackbot

    01/05/2022, 8:42 PM
    This message was deleted.
    m
    d
    • 3
    • 3
  • s

    Stylianos Gakis

    01/07/2022, 12:23 PM
    Is there something I can do for the use case of: I am observing a flow. I want to start an infinite loop when I receive a specific type (sealed, limited options) the flow gives me. When I get the same type again, I do not want to re-start this infinite loop but let it keep going. When I get a different type I want to stop that old infinite loop and do nothing until I again get the type I’m looking for. Code:
    sealed interface Types {
      object One : Types
      object Two : Types
    }
    val someFlow: Flow<Types>
    
    someFlow
      .filterIsInstance<Types.One>()
      .distinctUntilChanged()
      .collectLatest() { one ->
        // I want this to be cancelled on an emission of `Two` from `someFlow` but keep on going alive without interruption on a repeat emission of `One` if it was `One` before too
        coroutineScope {
          while(isActive) {
            doWork(one)
          }
        }
      }
    e
    • 2
    • 10
  • a

    Alexander Black

    01/19/2022, 2:53 AM
    can someone lead me to a way to collect a flow until some other flow emits something as a condition?? example:
    someFlow.onEach { /*Do something*/}.takeUntil(someOtherFlowAsPredicate).collect()
    b
    g
    n
    • 4
    • 9
  • c

    Ciprian Grigor

    01/19/2022, 9:29 PM
    Hi is there a way to know if there are active collectors on a SharedFlow? e.g. of a use case in Android app deciding how to show a notification if notificationFlow is collected by UI then the UI will show a snackbar if not (there are no active collectors) create a system notification
    b
    • 2
    • 2
  • j

    Justin Tullgren

    01/21/2022, 4:27 PM
    Hi. Am i understanding correctly that
    Channel.receiveAsFlow
    can process individual items in parallel by collectors? Or is it an internal "fan out". I just want to process a queue of emissions in parallel. Thanks!
    val flow = channel.receiveAsFlow()
    repeat(5) {  launch { flow.collect { /*receive channel item in separate coroutine */ } } }
    n
    s
    • 3
    • 3
  • j

    joadar

    02/05/2022, 4:54 PM
    Hello, I would like to pass a flow to another flow and collect the latest one:
    var running: Flow<Pair<Event, String?>> = flow {}
    
        suspend fun execute(node: NodeInterface) {
            running = node.run()
        }
    The first
    execute()
    is working, I collect it from running, but others call to
    execute()
    are not giving anything. How can I make it working correctly? What do I need to use? I tried with shareFlow, tried to collect the
    node.run()
    flow and emit to the
    running
    but nothing is collected 😕 Do I need to use channel instead of flow? Thanks for your input!
    n
    • 2
    • 5
  • h

    harry.singh

    02/08/2022, 5:04 PM
    Hey all! I'm learning how state flows work and trying to test something with the
    StateFlow
    . My test looks like this:
    @Test
    fun `test state flow`() = runBlocking {
        val stateFlow = flowOf(1, 2, 3)
            .onEach {
                println(it)
            }
            .stateIn(
                scope = TestCoroutineScope(),
                started = SharingStarted.WhileSubscribed(),
                initialValue = 0
            )
        
        val results = mutableListOf<Int>()
        val job = stateFlow.collectAsync(TestCoroutineScope()) {
            results.add(it)
        }
    
        assertEquals(listOf(0, 1, 2, 3, 4), results)
        
        job.cancel()
    }
    I was expecting this test to pass but it is failing. The actual size of results is
    1
    and the value it contains is
    3
    . I debugged my test with
    onEach
    and in console every value from the source flow is printed which means the value was emitted but it was never received in the collector. Does anybody know why am I only receiving the last value in my collector in the above code?
    n
    • 2
    • 7
  • t

    Tunji Dahunsi

    02/12/2022, 4:19 PM
    From the docs:
    A mutable state flow is created using MutableStateFlow(value) constructor function with the initial value. The value of mutable state flow can be updated by setting its value property. Updates to the value are always conflated. So a slow collector skips fast updates, but always collects the most recently emitted value.
    I was wondering does this behavior
    So a slow collector skips fast updates, but always collects the most recently emitted value.
    also apply to
    StateFlow
    instances created with the
    stateIn
    method?
    • 1
    • 1
  • a

    Alexander Maryanovsky

    02/16/2022, 10:44 AM
    Is there any particular reason why
    StateFlow/MutableStateFlow
    doesn’t implement
    ReadOnlyProperty/ReadWriteProperty
    ? It seems like it’s a perfect fit for a thread-safe property.
    t
    e
    • 3
    • 21
  • n

    Nick Allen

    02/17/2022, 8:25 AM
    Look at
    callbackFlow
    v
    • 2
    • 3
  • c

    Can Korkmaz

    02/22/2022, 2:30 PM
    Hello everyone, I've a problem with my flow getting stuck in viewmodel init block. The flow is declared inside dataStoreRepository class, which actually successfully emit's desired value. But after collecting flow, it doesn't proceed inside the coroutineScope. Shared the code in thread: here is to logcat after process death:
    t
    • 2
    • 4
Powered by Linen
Title
c

Can Korkmaz

02/22/2022, 2:30 PM
Hello everyone, I've a problem with my flow getting stuck in viewmodel init block. The flow is declared inside dataStoreRepository class, which actually successfully emit's desired value. But after collecting flow, it doesn't proceed inside the coroutineScope. Shared the code in thread: here is to logcat after process death:
Here is the code:
val suIdKeyFlow = dataStore.data.map { // this is dataStoreRepository class member
    it[PreferenceKeys.suIdKey] ?: 0
}
ViewModel member function:
private suspend fun readSuId(){
    storeRepository.suIdKeyFlow.collect {
        currentUserSuId.value = it
        Log.d("main", "current user su id flow: ${currentUserSuId.value}") // log is printed to logcat
    }
}
ViewModel init block:
init {
    Log.d("main","Main View Model created")// this gets printed to logcat

    viewModelScope.launch(<http://Dispatchers.IO|Dispatchers.IO>){
        Log.d("main","inside viewmodel coroutine scope 1")// this also gets printed to logcat
        readSuId()
        Log.d("main","inside viewmodel coroutine scope 2: --> ${currentUserSuId.value}}")// can't observe this log at logcat

        if(currentUserSuId.value != 0){
            getCurrentUser(currentUserSuId.value)
        }
    }
 isUserLoggedIn()// this sets isLoggedIn mutableState<Boolean> in viewmodel, and observed at composable for automatic login, not necessarily related to problem
        Log.d("main", "  user logged in : ${userLoggedIn.value}")
t

Tim Oltjenbruns

02/22/2022, 6:04 PM
Collect blocks until the flow closes
c

Can Korkmaz

02/23/2022, 7:55 AM
@Tim Oltjenbruns Thanks. Seems like I need to practice flows again.
t

Tim Oltjenbruns

02/23/2022, 12:44 PM
I’ve made the same mistake before. 🙂
View count: 6