Hey everyone. What’s the best way to filter nulls ...
# coroutines
k
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
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
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
Yes this sounds like a good solution.
k
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
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
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
What about using a SharedFlow then?
k
StateFlow
is a
SharedFlow
that only holds one value
m
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
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
Glad that i could help. Ok sounds like a reasonable reason.