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

    eygraber

    02/22/2021, 10:33 PM
    Is it bad practice to use
    MutableStateFlow
    to replace
    @Volatile var foo: Foo = defaultFoo()
    ? My main reasoning is that I don't like
    var
    and it would be easier for multiplatform etc...
    a
    • 2
    • 1
  • j

    joakim

    03/07/2021, 8:55 PM
    With Flow what is the "nicest" way to chain two network requests where the second depend on data from the first?
    w
    t
    • 3
    • 10
  • p

    ppvi

    03/09/2021, 11:54 AM
    We're thinking about adding guidance in Android about how to expose events/effects from a viewmodel and we need a flow that : • has a way to limit its capacity (usually 2-5) • replays everything in its capacity when going to 0 to 1 collectors but does not replay anything from 1 to 2 and beyond (as they're already consumed) We looked at
    SharedFlow
    (but it replays everything to a second observer),
    Channel(CONFLATED).*receiveAsFlow*
    but only one observer gets updates (and we discarded
    StateFlow
    ,
    consumeAsFlow()
    , and
    .broadcast()
    /cc @elizarov @Manuel Vivo
    e
    m
    • 3
    • 15
  • j

    Jason Ankers

    03/16/2021, 3:49 AM
    I have two data sources which I want to combine:
    private val workouts = flow { emit(userRepository.getWorkouts()) }
    private val exercises = flow { emit(userRepository.getExercises()) }
    
    val workoutsByExerciseId: Flow<Map<String, Workout>> = ? // do some transformation which combines both sources
    I want to create
    workoutsByExerciseId
    which should depend on both
    workouts
    and
    exercises
    . If either source changes,
    workoutsByExerciseId
    should always re-emit with the latest data. Which flow operator do I need here?
    n
    • 2
    • 1
  • j

    Jeff Lockhart

    03/16/2021, 5:31 AM
    I’m looking to convert some
    LiveData
    to
    StateFlow
    . What would be the equivalent flow construct for the
    CoroutineLiveData
    builder function?
    val state = liveData {
        emit(loadState())
    }
    
    suspend fun loadState(): State = withContext(<http://Dispatchers.IO|Dispatchers.IO>) {
        ...
    }
    The closest I can determine is:
    val state = flow {
        emit(loadState())
    }.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5000), null)
    Except that
    stateIn()
    requires an initial value, which doesn’t make this quite the same, as I don’t want any value collected until the state is loaded. Another possibility might be to use the
    shareIn()
    operator to create a
    SharedFlow
    with replay set to 1. This might be a closer equivalent in some ways:
    val state = flow {
        emit(loadState())
    }.shareIn(viewModelScope, SharingStarted.WhileSubscribed(5000), replay = 1)
    Except
    SharedFlow
    doesn’t provide a
    value
    property to get the current state. Which makes the
    StateFlow
    construct with a nullable type a closer equivalent in this regard.
    f
    • 2
    • 2
  • m

    Marc Knaup

    03/18/2021, 3:05 PM
    I’m using
    StateFlow
    in a Kotlin/React project and noticed an interesting nuance that may make it unsuitable for providing state in React-like projects - and maybe others. Am I missing something or do I have an error in my thinking here? In my case the problem crops up in the sign-in process. To simplify, there are just two pages: - The
    MembershipPage
    shows information about the signed-in user. If no user is signed in, redirect to
    SignInPage
    . - The
    SignInPage
    allows the user to sign in. If a user is already signed in, redirect to
    MembershipPage
    . A single
    UserController
    component wraps these (and other) user-related pages, keeps track of the signed-in user and provides that value to pages, and performs the redirects if needed. Various React components keep track of the signed-in user by accessing
    StateFlow.value
    when first rendering the component, and collect
    StateFlow
    emissions of new values to account for changes. Now when the user signs in the following happens: 1. Send credentials to server. 2. Server responds with OK and user object. 3.
    StateFlow
    value is set to signed-in user (
    flow.value = user
    ). 4.
    SignInPage
    redirects to
    MembershipPage
    . (user has signed in successfully) 5.
    UserController
    redirects to
    SignInPage
    . (not signed in) 6.
    SignInPage
    redirects to
    MembershipPage
    . (already signed in) 7.
    UserController
    redirects to
    SignInPage
    . (not signed in) 8. <repeats a few times> 9.
    SignInPage
    redirects to
    MembershipPage
    . (already signed in) 10.
    MembershipPage
    is presented. There’s a redirect cycle that gets broken automatically after a short time. What’s happening here? After a successful sign-in the `StateFlow`’s
    value
    is set to the signed-in user. From that moment on
    flow.value
    returns the signed-in user that was just set. The `StateFlow`’s emission of that new value however is not immediate and takes a while. During steps 4 through 8 above there is an inconsistent state in the React components. Those that happen to use
    StateFlow.value
    acknowledge that a user is signed in. Those that wait for the `StateFlow`’s emission of a new value still consider no user to be signed in. Depending on whether a component is first rendered (accessing
    .value
    ) or rerendered (value depends on
    .onEach/.collect
    ) the behavior is different. So by using
    StateFlow
    the system inadverently depends on two different sources of truth for the signed-in state. That’s because the return value of
    .value
    and
    StateFlow
    emissions of new value are not synchronized. I’m not sure if that’s intentional behavior of
    StateFlow
    . State should have a single source of truth and
    StateFlow
    itself is inconsistent here. One potential solution would be to change how
    StateFlow
    works. For example by having
    .value
    to not return a new value until the emission of the new value has begun. There’s still a potential for race between different contexts but at least in synchronous environments like JS that should be irrelevant. There are two possible approaches to use
    StateFlow
    as-is as a single source of truth: (1) Rely on
    .value
    only. (2) Rely on value emissions only. (1) doesn’t work because components need to know when the value changes in order to re-render. Otherwise the UI would get out of sync with the state. (2) doesn’t work because components need to access the current value synchronously at the time of initial render. Otherwise the UI would always have to briefly display a loading state while waiting for the initial emission even though that value is already available synchronously. As a compromise I could always rely on
    .value
    for accessing the current value and use emissions only for triggering a re-render. An inconsistency still remains however. Components aren’t notified immediately when the state they depend on changes. They either render a state that’s potentially newer than the state they were last notified about, or they render a state change too late, and they may render more often than needed. If the
    SignInPage
    executes some logic as a result of a successful sign-in it does so under the assumption that the user is signed in now. Other components however still assume that no user is signed in. No re-render is pending for them because there’s no notification about a change in state yet. Hence the UI is temporarily inconsistent. I don’t think that this subtle inconsistency between
    .value
    and emissions only affects Kotlin/React projects. It may also affects other projects which rely on a mix of accessing
    .value
    and emitted values. If it’s intentional then it should be communicated prominently in the documentation. However for me it would defeat the purpose of a
    StateFlow
    for managing state because it’s not a single source of truth. I could also write a wrapper that may use a
    StateFlow
    under the hood but synchronizes the current value with the emissions. But that’s just reinventing what I assume
    StateFlow
    is supposed to provide in the first place. What are your thoughts on that?
    e
    • 2
    • 82
  • f

    Francesco Cervone

    03/19/2021, 3:12 PM
    Hi everyone. I have a
    MutableStateFlow
    and I need to know when collectors subscribe/unsubscribe to/from this flow. I see the
    fun SharedFlow<T>.onSubscription
    extension which invokes the callback when the flow starts to be collected but I can’t find any extension function to know when a collector cancels the subscription. I’m basically looking for the equivalent of RxJava doOnSubscribe and doOnDispose. Does anyone know if there is a way to know when a collector cancels its subscription?
    n
    • 2
    • 2
  • s

    Simon Lin

    03/23/2021, 1:57 AM
    Can I receive most recently two value when a new value emit? for example: emit: 1, 2, 3, 4, 5, 6 downstream receive: [initValue, 1] [1, 2] [2, 3] [3, 4] [4, 5] [5, 6]
    e
    n
    • 3
    • 5
  • j

    Jason Ankers

    03/24/2021, 5:34 AM
    How can I propagate an upstream exception in a SharedFlow? For example, I have an Android screen which combines multiple data sources:
    val uiState = combine(sharedFlow1, sharedFlow2, sharedFlow2) { … }
    and I would like to catch anything which goes wrong in any of the flows. How could I achieve that?
    .catch
    doesnt work because shared flows never complete
    w
    • 2
    • 5
  • p

    ppvi

    03/24/2021, 10:33 AM
    I searched for this everywhere and I'm sure the answer is simple but... how do I check that a flow is empty inside
    runBlockingTest
    ?
    firstOrNull()
    shows
    IllegalStateException: This job has not completed yet
    👍 2
    e
    • 2
    • 1
  • b

    Bernardo Macêdo

    03/26/2021, 4:10 PM
    Hi everyone, I’m trying to find the best way to convert a
    LiveData
    that represents a UI state into a
    StateFlow
    . My initial live data code looked like this:
    private val _state = MediatorLiveData<State>().apply {
        addSource(livedata2) { value2 -> value?.let { it.copy(someVariable = value2) } }
        value = State(someVariable = "initial value", someOtherVariable = "another initial value")
    }
    val state: LiveData<State> = _state
    The idea is that I have an initial value and also part of the state gets updated whenever a new value is triggered on
    livedata2
    To reach the same behavior using flows, I modified
    livedata2
    to be a SharedFlow (I’ll call it
    flow2
    ) and my
    _state
    became a StateFlow. However I have to
    collect
    the flow2 instead of just applying an operator.
    private val _state = MutableStateFlow(
            State(
                someVariable = "initial value",
                someOtherVariable = "another intial value"
            )
        ).apply {
            viewModelScope.launch {
                flow2.collect { value2 -> emit(value.copy(someVariable = value2)) }
            }
        }
    
    val state: StateFlow<State> = _state
    While it does work, I feel like this is probably not the way to go? Maybe there’s an operator for that. (I tried to use
    _state.combine(flow2)
    but my state was not being updated for new events on
    flow2
    ) I there a better way to achieve the same result?
    m
    • 2
    • 3
  • s

    Sanendak

    04/07/2021, 5:31 PM
    Hello! I have MutableStateFlow (with string data as state) in PhoneStateListener class. I want to collect this flow in another class, where listener provides in constructor (repository). But this works only first time.
    b
    • 2
    • 4
  • t

    Tiago Nunes

    04/08/2021, 4:35 PM
    Hi everyone, is there a way to get the the previously emmited value of a flow in the onEach function, or something like this?
    private val refreshJob = filterFlow
        .onEach { prev, new ->
            if(prev.x != new.x) {
                updateX()
            }
        }
        .launchIn(viewModelScope)
    I know I can separate the filterFlow in multiple flows, which is probably the better way of solving my use case, but I'm still curious
    e
    • 2
    • 2
  • j

    Jeziel Lago

    04/13/2021, 2:46 PM
    What is the right way to testing a
    MutableSharedFlow
    ?
    @Test
        fun testIntSharedFlow() = runBlockingTest {
            val intSharedFlow = MutableSharedFlow<Int>()
    
            intSharedFlow.emit(5)
    
            assertEquals(5, intSharedFlow.single())
        }
    This code results
    java.lang.IllegalStateException: This job has not completed yet
    e
    j
    e
    • 4
    • 15
  • j

    Jason Ankers

    04/21/2021, 4:14 AM
    If I update a
    StateFlow
    value from
    Dispatchers.Main
    , and have some separate code collecting the flow also on
    Dispatchers.Main
    , can I guarantee that the collector receives the value immediately (synchronously) after the state flow emits?
    e
    • 2
    • 1
  • k

    kissed

    04/21/2021, 9:06 AM
    Hi everyone! Huge respect to JB! I have some question about StateFlow. What if I have 2 stateFlows and non-suspend transformer function, and I’d like to create a new StateFlow like a combination of theese two, transformed by the transformer function? It seems like current api does not allow to create such a StateFlow<>.combine operator? (sorry for bad English)
    w
    r
    • 3
    • 8
  • j

    jossiwolf

    04/30/2021, 6:02 PM
    Say I have a Flow of Booleans and only want to emit when they flip, what is the proper way to do that? What am I looking for?
    suspend fun Flow<Boolean>.flippedTo(value: Boolean, block: () -> Unit) {
        var previous: Boolean? = null
        collect { current ->
            if (previous == !value && current == value) {
                block()
            }
            previous = current
        }
    }
    boolFlow.flippedTo(false) {
        println("Flipped from true to false")
    }
    boolFlow.flippedTo(true) {
        println("Flipped from false to true")
    }
    j
    b
    • 3
    • 2
  • k

    Koya Sivaji

    04/30/2021, 8:04 PM
    Hi Everyone ! We have a legacy Android app in Java. Planning to rewrite some parts (DB and repository layer) in Kotlin. At one place , we have to access Kotlin Flow from java code. can you guys please direct me to any resource/link which talks about accessing Kotlin Flow from Java code ?
    a
    • 2
    • 1
  • b

    baxter

    05/07/2021, 4:51 PM
    One of my teammates ran into the following problem, which confused me at first until I realized what he did When you type out the code to collect on a flow (fully type out
    collect {}
    without auto-importing it), it'll default to the
    Flow.collect()
    method, which should be expected since the extension function
    collect {}
    was not imported. The problem is that when you do this, there's no option to automatically fix the issue unless you manually add the import statement, or re-type in "collect" but allowing auto-import to do its job. Now that I have seen this issue, I know how I can help my teammates next time, as we continue working with Coroutines/Flow. However, this was a minor point of frustration... So my question is: Is there any plan to rename or remove the
    Flow.collect
    function so this doesn't happen again? Screenshot is an example of how unhelpful lint is when you find yourself using
    Flow.collect()
    by accident
    r
    e
    • 3
    • 6
  • j

    Jeziel Lago

    05/11/2021, 6:12 PM
    Hi 👋🏼 How can I replace Rx operator
    repeat
    with some Flow operator?
    e
    • 2
    • 4
  • d

    darkmoon_uk

    05/13/2021, 4:03 AM
    Not entirely clear what you want but here's a
    Flow
    that emits something
    n
    times.
    flow { repeat(n) { emit(theThing) } }
    j
    • 2
    • 1
  • s

    sjj

    05/24/2021, 11:30 PM
    Hey folks 👋. I have a use-case where I construct a Flow that uses resources that can be expensive to initiate (e.g. queries from a database) but eventually completes (is not a continuous stream of data). I was hoping that I could use the
    shareIn
    operator to ensure the flow is only actually collected once, and subsequently cached. Based on what I've read, due to the fact that
    collect
    on a
    SharedFlow
    never actually returns, the recommended pattern is to use some kind of sentinel value to denote the completion of data and combine that with the
    takeWhile
    operator. Just wanted to check this is indeed the recommended solution.
    d
    d
    • 3
    • 3
  • m

    Mikael Alfredsson

    06/01/2021, 12:16 PM
    Im trying to switch between flows depending on another flow 🙂
    val result = state.transformLatest {
                when (it) {
                    "a" -> emitAll(emitter("A"))
                    "c" -> emitAll(emitter("C"))
                }
            }
    
            result.collect {
                println(it)
            }
    this will print a flow of A+<counter> or “C” +<counter> depending on the last value from “state”. I would like to ignore “unknown” states, but since transformLatest cancels the previous flow even if i don’t emit anything new, setting the state to “B” will just cancel the output, not continue on the previous selected output. Is there a nice way to achieve what I want?
    w
    d
    b
    • 4
    • 8
  • n

    ninad thakare

    06/14/2021, 2:20 PM
    I want MutableSharedFlow to keep the values 1, 2 in it’s buffer if no one is collecting it.
    g
    t
    • 3
    • 8
  • f

    Francisco

    06/15/2021, 4:35 AM
    Hi 👋 I'm learning flows, and I have the following question. Is it possible for a flow to be collected by two different coroutines concurrently? I want the following properties • a collector shouldn't affect the other one • I want the flow to be able to use
    Conflation
    in case one of the collector is being to slow • flow is generated once (meaning I don't want to compute each item in the flow twice) I was able to do this using broadcast channel and consuming it as channel like
    openSubscription().consumeAsFlow().conflate()
    . Is is possible to do something similar to this using flows? Thanks!
    d
    • 2
    • 6
  • c

    Ciprian Grigor

    06/25/2021, 12:41 PM
    Hi, what would be the best approach to unsubscribe/cancel a flow once a certain item/condition is reached, but returning that last item: transformWhile?
    g
    • 2
    • 1
  • r

    Robert Wijas

    07/02/2021, 1:53 PM
    /**
     * Implements function from
     * [RxJava](<http://reactivex.io/RxJava/3.x/javadoc/io/reactivex/rxjava3/core/Observable.html#throttleLatest-long-java.util.concurrent.TimeUnit->)
     */
    internal fun <T> Flow<T>.throttleLatest(timeout: Duration) =
        conflate().transform {
            emit(it);
            delay(timeout);
        }
    Hey, am I missing any flaws in this implementation? Thx 👋
    e
    • 2
    • 10
  • j

    Jérémy CROS

    07/05/2021, 1:50 PM
    Hi guys 🙂 I just had a small argument with myself regarding how to expose a flow in an interface. The implementation is backed by a shared flow. Obviously, no
    MutableSharedFlow
    exposed. But would you have a
    SharedFlow
    exposed? Since the consumer may need to know that it’s hot? Or a regular
    Flow
    ? Since the consumer is just going to ‘.collect()’ anyway? Or is it a case by case discussion?
    g
    • 2
    • 5
  • e

    ebukreev

    07/06/2021, 7:47 AM
    Hi 👋 does anyone know why asSharedFlow function may not be found during compilation? kotlin version 1.5.20, kotlinx-coroutines-core tried 1.4.1 and 1.5.0
    l
    • 2
    • 2
  • c

    Chris Fillmore

    07/20/2021, 8:59 PM
    Hi folks. Question about using SharedFlow: sometimes I want to apply
    filter
    or
    map
    , but these return regular `Flow`s, but I still want to use a SharedFlow. I know I can call
    stateIn
    or
    shareIn
    to turn them back into a StateFlow/SharedFlow, but this requires that I pass some arguments, when what I really want is for the same SharedFlow I had before, except with these filters/maps applied. Am I missing something? Is there a better way to map/filter a SharedFlow?
    w
    e
    • 3
    • 3
Powered by Linen
Title
c

Chris Fillmore

07/20/2021, 8:59 PM
Hi folks. Question about using SharedFlow: sometimes I want to apply
filter
or
map
, but these return regular `Flow`s, but I still want to use a SharedFlow. I know I can call
stateIn
or
shareIn
to turn them back into a StateFlow/SharedFlow, but this requires that I pass some arguments, when what I really want is for the same SharedFlow I had before, except with these filters/maps applied. Am I missing something? Is there a better way to map/filter a SharedFlow?
w

wasyl

07/20/2021, 10:00 PM
What's some example use case you need this for?
e

ephemient

07/20/2021, 10:23 PM
if your transformations are stateless, then it shouldn't matter how many times the resulting flow is subscribed, even if it's not a "StateFlow". if they're stateful, you should probably declare what dispatcher they run on anyway…
c

Chris Fillmore

07/21/2021, 12:53 AM
Thanks for responding! Sorry I realize my question is more about
StateFlow
specifically, since I have some code which accesses
value
directly. But, as it turns out, when I tried to write some example describing what I’d like to do, I realized that it did not make sense to filter/map a state flow into another state flow. So thanks anyhow!
👍 1
View count: 4