Is there a way to make a transformation of Flow wi...
# coroutines
a
Is there a way to make a transformation of Flow with a statefull collector? I am migrating kmath streaming API to flow and I need to implement a chunking and windowing operation (take
n
subsequent elements and join them into one).
m
I'm not too familiar with the API yet, but maybe something like this will work?
Copy code
fun <T> Flow<T>.chunked(chunkSize: Int) = flow {
    val mutList = mutableListOf<T>()
    collect { elem ->
        mutList.add(elem)
        if (mutList.size == chunkSize) {
            emit(mutList.toList())
            mutList.clear()
        }
    }
    
    // Emit the final chunk if there are elements left
    if (mutList.isNotEmpty()) {
        emit(mutList.toList());
    }
}
a
Yes, I am currently writing something quite alike, but I was wondering if there out-of-box solutions