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

albertosh

02/02/2021, 1:29 PM
Hi everyone! Some time ago,
Flow.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
Copy code
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
Copy code
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 Jetpack
d

Dominaezzz

02/02/2021, 3:24 PM
Instead of emitAll use collect and emit, then you can set an isEmpty flag.
👍 1
2 Views