https://kotlinlang.org logo
#flow
Title
# flow
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:
Copy code
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.
Copy code
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

miqbaldc

03/27/2021, 9:51 AM
b

Bernardo Macêdo

03/27/2021, 10:06 AM
Thanks @miqbaldc I’ve read the article, but it is giving guidance on how to collect the flows on the view layer safely (considering the fragment/activity lifecycle). But in this case, I’m trying to merge together 2 sources of information on the
viewModel
layer. The resulting stateFlow will actually be collected automatically using data binding in my implementation. I still wonder if there is an operator that allows me to replace the
.addSource
usage effectively without the need to collect the intermediate flow (
flow2
in this case)
🙏 1
m

miqbaldc

03/27/2021, 10:16 AM
Ah I see, looks like we need to wait for either Google add an API extensions as alternative of
addSource
when using
Flow
:(