kissed
04/21/2021, 9:06 AMwasyl
04/21/2021, 9:13 AMStateFlow
back. It would mean that every time you set value in one of the combined (source) flows, the resulting one would need to run the transform function to provide proper value
. But since the source flows can’t push value downstream, it’s the downstream that needs to be collecting. Just calling combine
can’t start collecting because collection needs to happen in a scopecombine
and later stateIn
to launch the flow, and provide the default value as well. Since you know that the two source flows are StateFlows, you can just do the same transform as for combine
kissed
04/21/2021, 9:17 AMwasyl
04/21/2021, 9:20 AMval myValue get() = combineFun(flow1.value, flow2.value)
kissed
04/21/2021, 9:21 AMRidwan Farouki
04/23/2021, 8:59 AMCoroutineScope
as receiver for scheduling the transformation function itself.
fun <T1, T2, R> CoroutineScope.combineState(
flow1: StateFlow<T1>,
flow2: StateFlow<T2>,
sharingStarted: SharingStarted = SharingStarted.Eagerly,
transform: (T1, T2) -> R
): StateFlow<R> = combine(flow1, flow2) { o1, o2 ->
transform.invoke(o1, o2)
}.stateIn(this, sharingStarted, transform.invoke(flow1.value, flow2.value))