Hello, everyone! Is there a way to apply the `.map...
# coroutines
g
Hello, everyone! Is there a way to apply the
.map
operator or something similar to a
StateFlow
and get another
StateFlow
back?
Sounds like the recommendation is to use
map { ... }.stateIn(...)
g
Thank you for the answer, but I'm not sure it applies to my use case. This doesn't mesh well with DataBinding, as I'd need my ViewModel to have access to a CoroutineScope instead of having the collector handle this.
My viewmodels are not AAC ones, btw.
Also, .stateIn is a suspending function.
s
There's a non-suspending version if you provide an initial value, which should be easy to do if you're mapping from an existing
StateFlow
. I can see that it's inconvenient to have to provide a
CoroutineScope
, but I think it's unavoidable. Since the resulting
StateFlow
is a shared flow, the work to compute its values always has do be done by the producer, not by the consumer.
Are you able to use the built-in extension scopes? I'm not sure what you meant by "not AAC", I'm not very familiar with android.
g
AAC means Android Architecture Components. I'm not able to use the extensions you mentioned because my view models don't inherit from ViewModel.
👍 1
Interesting that you have to provide a scope when converting from a Flow to a StateFlow but not when creating one from scratch. There's probably something I'm missing.
s
If you create your own
MutableStateFlow
then whatever code you write to set values on that flow is acting as the producer. It may not necessarily be a coroutine, but something besides the consumer is doing the work to provide the values.
1
I guess one way to think about it is: if you turned a flow into a
StateFlow
by hand, by collecting values from the flow and setting them on a
MutableStateFlow
, you'd have to launch a coroutine to do that.
1
g
Ohh, thanks a lot! Now I get it.