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

    Michael Granger

    06/07/2022, 8:41 PM
    Does anyone know any any example code for hooking up Channels/Flows to a socket? I.e., I have a socket in a WearOS 3 app I want to wrap in a receive Channel that is a producer for various flows in viewmodels, and a send channel that the viewmodels can use in callbacks.
    • 1
    • 1
  • v

    Vivek Modi

    06/09/2022, 3:03 PM
    Hey guys, I am using
    MutableStateFlow
    in my project. When we initialise the
    MutableStateFlow
    object we need to give default value.
    val topics = MutableStateFlow<List<String>>(emptyList())
    when I collect this value
    [null, "Hello", "world"]
    I want to pass this list in
    adapter
    . So is there a way we can remove the null object before passing in adapter or Is there any better way ?
    viewModel.topics.collect { topicsList ->
        println(topicsList)         // [null, "Hello", "world"]
        adapter.submitList(topicsList)
    }
    d
    e
    d
    • 4
    • 6
  • v

    Vikas Singh

    06/09/2022, 7:10 PM
    Is it required to use the repeatOnLifeycle with state flow collecting in the UI ? As I am updating the UI only when it is visible on the screen.
    e
    e
    • 3
    • 2
  • c

    Colton Idle

    06/09/2022, 11:14 PM
    In my App, I have an AppState. AppState contains
    currentUser = Flow<User>
    Would this be better represented as a StateFlow?
    e
    f
    d
    • 4
    • 6
  • p

    Peter Mandeljc

    06/16/2022, 2:58 PM
    hey, I would need help with custom flow transformation. I would basically need something like
    distinctUntilChanged()
    , with the exception, to re-emit same value, after certain amount of time has passed. How would I achieve that?
    time [sec], input values, emitted value
    0, "A", "A"
    1, "A", <no emission>
    2, "A", <no emission>
    3, "A", "A"
    4, "B", "B"
    e
    • 2
    • 5
  • a

    Aidan Low

    06/21/2022, 5:29 PM
    If I turn regular Flows into StateFlows
    stateFlow1
    and
    stateFlow2
    via
    .stateIn(started = SharingStarted.WhileSubscribed)
    and then create
    stateFlowCombined = stateFlow1.combine(stateFlow2).startIn(started = SharingStarted.WhileSubscribed)
    then will subscribing to
    stateFlowCombined
    transitively subscribe to
    stateFlow1
    and
    stateFlow2
    ? I'm struggling with writing unit tests to verify behavior that works fine in our production app.
    n
    • 2
    • 11
  • a

    AmrJyniat

    06/24/2022, 12:19 PM
    How to reflect a flow value when it gets ready after collecting?
    var property: String? = null
    .......
    
    propertyFlow.collect{
        property = it
    }
    
    .......
    
    textView.text = property // reflect this value when its get ready
    Something like that, any idea?
  • v

    Vikas Singh

    06/27/2022, 5:59 AM
    I have a case where I am assigning the stateflow in viewmodel to the usecase stateflow like below class TestModel: ViewModel() { private var discoverTag = MutableStateFlow(false)
    fun initiate(){
    viewModelScope.launch {
    discoverTag = usecase.tag
    }
    }
    Where
    tag
    is stateflow in usecase which emits the value The problem here is that the discover tag is only collected for the first time but not when emitted from usecase
    j
    • 2
    • 1
  • c

    Colton Idle

    07/28/2022, 3:36 AM
    This question didn't get much traction in #coroutines so i figure that id ask here. I'm joining a project that has a bit of a flow hell going on. Bunch of flows started off of other flows. collect instead of collectLatest being used in some places. I was just wondering if anyone had any debugging tips or something to be able to tell how many flowables are still being collected. what hot flowables are still emitting without their being an observer. etc. Are logs my only hope here?
  • a

    AmrJyniat

    07/28/2022, 9:07 AM
    Is there a real way to recollect the
    Flow
    each x seconds? like:
    val flow = flow {
        emit(doApiCall())
    }
    .onEach{ delay(1000) }// something like that
    ........
    flow.collect{
      //get flow value
    }
    I searched a lot but it seems that I need to put the code in fun and call it each time, what do you think?
    e
    d
    • 3
    • 8
  • r

    Robert Wijas

    07/28/2022, 4:14 PM
    I have a flow that emits when value changes. That value is mapped to a value with optional expiration date. I want to emit recalculated value when the last value expires. My current solution is recursive and I don’t really like that.
    fun myFlow(): Flow<B> =
      valueFlow()
        .map { B(it) } // B is the type with expiration date
        .flatMapLatest { value ->
          flow {
            emit(value)
            value.timeToExpiration?.let {
              delay(it)
              emitAll(myFlow()) // !recursion
            }
          }
        }
    Any hints how to remove recursion? Thx.
  • l

    Landry Norris

    07/28/2022, 4:29 PM
    This may be a stupid question, but is there a concise way to convert a List<Flow<T>> to a Flow<List<T>> that emits a value when any flow in the list emits a value?
    r
    d
    • 3
    • 4
  • l

    Landry Norris

    08/05/2022, 3:02 PM
    When I call MutableStateFlow.update {}, isn’t function() called on the same thread? I’m running into an issue when my code looks like the pseudocode in the 🧵 [Solved] function() is called on the same thread, some other code changed my variable that I missed before calling state.update
    b
    • 2
    • 4
  • a

    althaf

    08/21/2022, 4:28 AM
    hi , It ok to do this in a single launch ? or do we have to use separate launch for repeat on life cylce ?
    lifecycleScope.launch {
    
        lifecycle.repeatOnLifecycle(Lifecycle.State.STARTED) {
            loginAuthorizationViewModel.onLoginSuccessful.collect {
                startActivity(HomeActivity.getDefaultIntent(this@LoginActivity))
                finish()
            }
        }
    
        lifecycle.repeatOnLifecycle(Lifecycle.State.STARTED) {
            loginInputValidationViewModel.onPasswordInvalid.collect {
                enableViews(true)
                et_password.error = it
            }
        }
    
        lifecycle.repeatOnLifecycle(Lifecycle.State.STARTED) {
            loginAuthorizationViewModel.onLoginFailure.collect {
                enableViews(true)
                showMessage(it.toString())
            }
        }
    
        lifecycle.repeatOnLifecycle(Lifecycle.State.STARTED) {
            loginInputValidationViewModel.onUserNameInvalid.collect {
                enableViews(true)
                tv_user_name.error = it
            }
        }
    
        lifecycle.repeatOnLifecycle(Lifecycle.State.STARTED) {
            loginInputValidationViewModel.onValidationSuccessful.collect {
                loginAuthorizationViewModel.requestLogin(
                    userName = it.first,
                    password = it.second
                )
            }
        }
    s
    • 2
    • 2
  • n

    Natalia Chuzhmarova

    09/07/2022, 7:49 AM
    Hi there! I'm having issues trying to implement caching with Flow. Requirements: return a cached value and then follow up with network request result. The cached value must be observed regardless of network call success or failure. Implementation looks like
    fun data(): Flow = flowOf(
        flowOf(cachedValue),
        networkCallFlow
    ). flattenConcat()
    which is then observed in a ViewModel and mapped to UI state
    data()
    .onEach { .. }
    .map { uiState(data) }
    .catch { emit(uiState(error)) }
    It works fine when the network call succeeds. The problem is, when
    networkCallFlow
    throws an exception (no network), the
    cachedValue
    is never mapped, however it triggers the
    onEach
    handler. My guess is that the emission of the
    cachedValue
    does not guarantee that it will be observed, and the exception halts the Flow before the consumption of the
    cachedValue
    happens or while it is in progress. Is my understanding correct? Is there any way to adjust the Flow to fit the requirements? The code: https://pl.kotl.in/3U8jVprL-
    e
    f
    • 3
    • 12
  • j

    jozefdransfield

    09/12/2022, 2:39 PM
    Hello All, I might be missing something but what is the difference between a flow generated from flow { … } and a ReceiveChannel.receiveAsFlow() im seeing some behavour i dont understand, namely if i create multiple new flows based on filters, the regular flow one receives all the messages, this isnt the case when they come from a receive channel. I have a unit test to replicate what im seeing if it helps?
    n
    • 2
    • 1
  • a

    althaf

    09/17/2022, 7:11 AM
    I"m not able to use coroutine Context, in the flowOn(....), app is crashing with
    java.lang.IllegalArgumentException: Flow context cannot contain job in it. Had [SupervisorJobImpl{Active}@7b4ca1f, <http://Dispatchers.IO|Dispatchers.IO>]
    interface UseCaseScope : CoroutineScope {
        override val coroutineContext: CoroutineContext
            get() = SupervisorJob() + <http://Dispatchers.IO|Dispatchers.IO>
    }
    The intention here is to cancel the coroutine context when we business logic need to cancel it. So that i can call coroutineContext.cancel()
    class LoginUseCase(private val authRepository: AuthRepository) : FlowUseCase<LoginRequest, Boolean>() {
    
        override fun execute(parameter: LoginRequest): Flow<Result<Boolean>> =
            flow {
                authRepository.login(parameter.username, parameter.password).collect { response ->
                    this.defaultResultHandler(onSuccess = {
                        emit(Result.success(true))
                    }, response)
                }
            }.flowOn(coroutineContext)
    
        override fun cancel() {
            coroutineContext.cancel()
        }
    }
    ^^^ will cause app the crash Or is this is the way to execute my intention, and ignore flowOn(.....) , i'm really confused here
    class LoginUseCase(private val authRepository: AuthRepository) :
        FlowUseCase<LoginRequest, Boolean>() {
    
        override fun execute(parameter: LoginRequest): Flow<Result<Boolean>> =
            flow {
    >>>>         launch(coroutineContext) {
                    authRepository.login(parameter.username, parameter.password).collect { response ->
                        this@flow.defaultResultHandler(onSuccess = {
                            emit(Result.success(true))
                        }, response)
                    }
                }
            }
    
        override fun cancel() {
    >>>    coroutineContext.cancel()
        }
    }
    m
    • 2
    • 1
  • s

    Suraj Sahani

    09/28/2022, 3:52 AM
    Flow is the mental state
  • s

    Sam Stone

    10/12/2022, 2:17 AM
    How do you collect a flow once in a non-blocking way, so it doesn't update when the flow updates?
    m
    n
    • 3
    • 4
  • z

    Zach

    10/14/2022, 7:25 PM
    I have a
    stateFlow
    that combines two
    snapshotFlow
    that works when running on device, but when I attempt to unit test with turbine, it never emits more than once. Am I doing something wrong or am I going down the wrong path?
    fun validInput() = runTest {
        viewModel.screenState.test {
            assertEquals(awaitItem(), EnterNameScreenState.EnterNameLoadingResults) // passes
            viewModel.firstNameInputValidation("test")
            // fails, waited too long
            assertEquals(awaitItem(), EnterNameScreenState.EnterNameLoadedResults(InputWrapper(value = "test"), InputWrapper(), false)). 
        }
    }
    m
    k
    • 3
    • 10
  • a

    AmrJyniat

    10/19/2022, 8:44 AM
    Anyone can help with this question related to Flow
    retry
    mechanism?
  • v

    Victor Collod

    10/27/2022, 3:30 PM
    Hello 🙂 I'm trying to use MutableStateFlow to log state updates but I can't quite pull it off: • I'm starting a collect job with launch, but I can't figure out how to be sure the collect job will be started before the first update comes (I could use a condition variable but it feels pretty overkill). I'm using yield() to help make it happen, but it feels very hacky • how can I make sure the updates get delivered to the collector once it is subscribed?
  • v

    Victor Collod

    10/27/2022, 4:07 PM
    Would running all of it unconfined be appropriate?
    m
    • 2
    • 5
  • e

    elye

    10/31/2022, 6:48 AM
    Not sure if I should ask in compose or here, but cross share it https://kotlinlang.slack.com/archives/CJLTWPH7S/p1667198842541229
  • m

    Marc Knaup

    11/03/2022, 8:03 PM
    Is there a better way to “launch flow collection but suspend until the collection is ready”? Without this workaround (i.e.
    .onEach { … }.launchIn(…)
    ) elements can be missed if they’re emitted shortly after this.
    e
    c
    • 3
    • 4
  • r

    Rihards

    11/11/2022, 1:02 PM
    Hi! I have an issue with
    StateFlow
    -> when I open the screen for the first time and do actions to emit new values then value is updated, but when I re-open the view then value is not updated to initial value, but old value is still there. This is the way I try to keep the state up to date:
    private val valueChanges: MutableSharedFlow<Int> = MutableSharedFlow(
      extraBufferCapacity = 1, onBufferOverflow = BufferOverflow.DROP_OLDEST
    )
    
    private val valueState: StateFlow<Int> = valueChanges
      .stateIn(scope, SharingStarted.Eagerly, 0)
    Then at the very beginning of the whole flow I call this function where
    changes
    is
    valueChanges
    flow:
    updateChangesOnStart(changes: Flow<Int>) = changes
      .onStart { emit(0) }
    To update the state later I use:
    scope.launch{
      valueChanges.emit(${passed number})
    }
    Is the scope the one that does not allow me to update the value when function is reused?
    y
    • 2
    • 1
  • r

    Racci

    11/16/2022, 7:35 AM
    So i've built an EventBus around flows and I'm trying to implement a priority of subscriptions would there be a good way to implement this?
    c
    • 2
    • 5
  • l

    Lukas Lechner

    11/23/2022, 3:08 PM
    Hi! I created a new video about “What is a Flow in Kotlin?”

    https://youtu.be/TvdF566t2Y8▾

    f
    c
    • 3
    • 3
  • l

    liminal

    12/27/2022, 3:49 AM
    Hi, how would I emit an error into my MutableStateFlow for testing?
    g
    • 2
    • 3
  • l

    liminal

    12/27/2022, 4:26 PM
    When dealing with a StateFlow in ViewModel, stateIn vs collect: the benefit of using stateIn is the “started” param which lets you resubscribe to keep the stream alive on configuration changes. Correct? Any other considerations?
Powered by Linen
Title
l

liminal

12/27/2022, 4:26 PM
When dealing with a StateFlow in ViewModel, stateIn vs collect: the benefit of using stateIn is the “started” param which lets you resubscribe to keep the stream alive on configuration changes. Correct? Any other considerations?
View count: 11