Created
December 7, 2022 18:25
-
-
Save LouisCAD/3ff868c8cb1ee1ff4bd855b11ea65715 to your computer and use it in GitHub Desktop.
Cut a Flow into chunks for batch processing.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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