albertosh
02/02/2021, 1:29 PMFlow.onEmpty
operator was added (https://github.com/Kotlin/kotlinx.coroutines/issues/1890)
Is there any plan for including Flow.onNotEmpty
?
Use case is a method that return paginated data and you need all the items
fun getData(page: Int, pageSize: Int): Flow<Item> = ...
fun getAllData() = getAllData(0, 5)
private fun getAllData(page: Int, pageSize: Int): Flow<Item> = flow {
val data = getData(page, pageSize)
emitAll(data)
data.onNotEmpty { emitAll(getAllData(page + 1, pageSize) }
}
Maybe I’m not following a proper approach, some other ideas I had using count
private fun getAllData(page: Int, pageSize: Int): Flow<Item> = flow {
val data = getData(page, pageSize)
emitAll(data)
if (data.count() == pageSize) { // Since `count` does a `collect`, another flow is created
emitAll(getAllData(page + 1, pageSize)
}
}
To avoid creating two flows per page, I tried with a SharedFlow
but since it never ends you can’t invoke count
BTW, I’m intending to use it on backend side, so not sure if I can use the Paging Library from JetpackDominaezzz
02/02/2021, 3:24 PM