Bernardo Macêdo
03/26/2021, 4:10 PMLiveData
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?miqbaldc
03/27/2021, 9:51 AMBernardo Macêdo
03/27/2021, 10:06 AMviewModel
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)miqbaldc
03/27/2021, 10:16 AMaddSource
when using Flow
:(