Home > database >  Why does the combine operator of flow works with arrays?
Why does the combine operator of flow works with arrays?

Time:04-14

Why does the combine operator of flow works with arrays(instead of list or iterator)?

From source code:

public inline fun <reified T, R> combine(
    flows: Iterable<Flow<T>>,
    crossinline transform: suspend (Array<T>) -> R
): Flow<R> {
    val flowArray = flows.toList().toTypedArray()
    return flow {
        combineInternal(
            flowArray,
            arrayFactory = { arrayOfNulls(flowArray.size) },
            transform = { emit(transform(it)) })
    }
}

CodePudding user response:

I guess it's just for convenience, because most combine... methods use vararg flows: Flow<T> parameter and call combineInternal() function, and it is convenient just to pass flows to combineInternal() method without converting it to another data structure. Example of a method, which accepts vararg flows: Flow<T> parameter:

public inline fun <reified T, R> combine(
    vararg flows: Flow<T>,
    crossinline transform: suspend (Array<T>) -> R
): Flow<R> = flow {
    combineInternal(flows, { arrayOfNulls(flows.size) }, { emit(transform(it)) })
}
  • Related