Skip to content

Instantly share code, notes, and snippets.

@LouisCAD
Created December 7, 2022 18:25
Show Gist options
  • Save LouisCAD/3ff868c8cb1ee1ff4bd855b11ea65715 to your computer and use it in GitHub Desktop.
Save LouisCAD/3ff868c8cb1ee1ff4bd855b11ea65715 to your computer and use it in GitHub Desktop.
Cut a Flow into chunks for batch processing.
import kotlinx.coroutines.*
import kotlinx.coroutines.channels.*
import kotlinx.coroutines.flow.*
fun <T> Flow<T>.chunked(size: Int): Flow<List<T>> = flow {
val elements = ArrayList<T>(size)
collect {
elements.add(it)
if (elements.size == size) {
emit(elements.toList())
elements.clear()
}
}
if (elements.isNotEmpty()) emit(elements)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment