https://kotlinlang.org logo
#coroutines
Title
# coroutines
n

nwh

05/04/2019, 12:58 AM
Not sure if this is the best place to post, but I thought
Flow
could use a
chunked
method, just like
List
has:
Copy code
fun <T> Flow<T>.chunked(size: Int) = flow {
	val list = mutableListOf<T>()
	collect {
		list.add(it)
		
		if (list.size == size) {
			emit(list.toList())
			list.clear()
		}
	}
	
	if (list.isNotEmpty())
		emit(list)
}
Might be good to include in the standard library. Loving the API 👍🏻
l

louiscad

05/04/2019, 10:26 AM
Adding the explicit return type would help 😉
n

nwh

05/04/2019, 3:38 PM
True!
Copy code
fun <T> Flow<T>.chunked(size: Int): Flow<List<T>> = flow {
    val list = mutableListOf<T>()
    collect {
        list.add(it)
        
        if (list.size == size) {
            emit(list.toList())
            list.clear()
        }
    }
    
    if (list.isNotEmpty())
        emit(list)
}
3 Views