Search code examples
kotlincollectionskotlin-flow

Combine two state flows into new state flow


I have two state flows. Is it possible to combine them and get new state flow? Logically it should be possible because both state flows have initials values, but as I see combine function returns just Flow and not StateFlow.


Solution

  • So far I created function:

    fun <T1, T2, R> combineState(
            flow1: StateFlow<T1>,
            flow2: StateFlow<T2>,
            scope: CoroutineScope = GlobalScope,
            sharingStarted: SharingStarted = SharingStarted.Eagerly,
            transform: (T1, T2) -> R
    ): StateFlow<R> = combine(flow1, flow2) {
        o1, o2 -> transform.invoke(o1, o2)
    }.stateIn(scope, sharingStarted, transform.invoke(flow1.value, flow2.value))