Skip to content

Instantly share code, notes, and snippets.

@LouisCAD
Created December 7, 2022 18:25
Show Gist options
  • Select an option

  • Save LouisCAD/3ff868c8cb1ee1ff4bd855b11ea65715 to your computer and use it in GitHub Desktop.

Select an option

Save LouisCAD/3ff868c8cb1ee1ff4bd855b11ea65715 to your computer and use it in GitHub Desktop.

Revisions

  1. LouisCAD created this gist Dec 7, 2022.
    15 changes: 15 additions & 0 deletions Flow.chunked.kt
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,15 @@
    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)
    }