https://kotlinlang.org logo
#coroutines
Title
# coroutines
k

Kurt Renzo Acosta

11/26/2020, 6:55 AM
Hey everyone. What’s the best way to filter nulls for StateFlow? I have this:
Copy code
private val _myFlow = MutableStateFlow<String?>(null)
val myFlow: Flow<String> get() = _myFlow.filterNotNull()
But I want to expose the flow as a
StateFlow
to the consumer. I can use
asStateFlow()
but I can’t use
filterNotNull()
anymore as it converts it back to a
Flow
m

Manuel Wrage

11/26/2020, 8:17 AM
How should that work? The current value must be always present if you could do this what would be the initial value for the non null flow?
k

Kurt Renzo Acosta

11/26/2020, 8:18 AM
Yeah the initial value would come asynchronously after a network call which is why it’s null. Would you suggest having it as an empty string instead?
m

Manuel Wrage

11/26/2020, 8:19 AM
Yes this sounds like a good solution.
k

Kurt Renzo Acosta

11/26/2020, 8:20 AM
But what if I have a pojo instead where I can’t just put out an empty string or a -1 for an int?
m

Manuel Wrage

11/26/2020, 8:23 AM
Either create a dummy default value like you would do with string or just don't use an StateFlow at all. Is there a specific reason why you want this to be a StateFlow?
k

Kurt Renzo Acosta

11/26/2020, 8:24 AM
correct me if i’m wrong but by my understanding, every consumption of the flow would create an instance of that
Flow
as compared to using
StateFlow
or
SharedFlow
where values are just replayed
m

Manuel Wrage

11/26/2020, 8:26 AM
What about using a SharedFlow then?
k

Kurt Renzo Acosta

11/26/2020, 8:28 AM
StateFlow
is a
SharedFlow
that only holds one value
m

Manuel Wrage

11/26/2020, 8:30 AM
Yes but if u use a
SharedFlow
you wouldn't need to provide an initial value but the flow would still be shared.
Why you want the Flow to be shared?
k

Kurt Renzo Acosta

11/26/2020, 8:31 AM
Ahhh you are right. Thanks for pointing me there. I’m gonna fiddle around with it
I have multiple consumptions in my views.
Copy code
viewModel.flow
    .onEach { ... }
    .launchIn(...)

viewModel.flow
    .combine(viewModel.flow2) { ... }
    .onEach { ... }
    .launchIn(...)
Again, if my understanding is correct, consuming both of those that way would run two instances of that
Flow
as compared with using
StateFlow
/
SharedFlow
which would just replay and share values so I saw it as a way to optimize things.
m

Manuel Wrage

11/26/2020, 8:38 AM
Glad that i could help. Ok sounds like a reasonable reason.
5 Views