/** Copyright 2025 takahirom Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ public inline fun CoroutineScope.buildSingleSourceStateFlow( sourceStateFlow: StateFlow, crossinline buildBlock: (T) -> R ): StateFlow { val getSourceValueArray: () -> Array<*> = { arrayOf(sourceStateFlow.value) } val callBuildBlockByCurrentSource: () -> R = { buildBlock(sourceStateFlow.value) } val convertedStateFlow = sourceStateFlow.map { getSourceValueArray() to buildBlock(it) }.stateIn( this, DefaultWhileSubscribed, getSourceValueArray() to callBuildBlockByCurrentSource() ) return buildStateFlow( callBuildBlockByCurrentSource = callBuildBlockByCurrentSource, getSourceValueArray = getSourceValueArray, convertedStateFlow = convertedStateFlow ) } public inline fun CoroutineScope.buildSingleSourceStateFlow( sourceStateFlow1: StateFlow, sourceStateFlow2: StateFlow, crossinline buildBlock: (T1, T2) -> R ): StateFlow { val getSourceValueArray: () -> Array<*> = { arrayOf(sourceStateFlow1.value, sourceStateFlow2.value) } val callBuildBlockByCurrentSource: () -> R = { buildBlock(sourceStateFlow1.value, sourceStateFlow2.value) } val convertedStateFlow = combine(sourceStateFlow1, sourceStateFlow2) { s1, s2 -> getSourceValueArray() to buildBlock(s1, s2) }.stateIn( this, DefaultWhileSubscribed, getSourceValueArray() to callBuildBlockByCurrentSource() ) return buildStateFlow( callBuildBlockByCurrentSource = callBuildBlockByCurrentSource, getSourceValueArray = getSourceValueArray, convertedStateFlow = convertedStateFlow ) } fun buildStateFlow( callBuildBlockByCurrentSource: () -> R, getSourceValueArray: () -> Array<*>, convertedStateFlow: StateFlow, R>> ): StateFlow { return object : StateFlow { override val replayCache: List get() { return listOf(value) } override val value: R get() { val result = callBuildBlockByCurrentSource() return result } override suspend fun collect(collector: FlowCollector): Nothing { if (!getSourceValueArray().contentDeepEquals(convertedStateFlow.value.first)) { convertedStateFlow.first { it.first.contentDeepEquals(getSourceValueArray()) } } convertedStateFlow.collect { collector.emit(it.second) } } } }