Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin Flow only collect every second

I have a Flow which downloads a file. The flow emits the download progress. I want to show the progress in the phone notification center, but only update the value once every second to prevent lagging the device.

My Flow:

return callbackFlow {
  someJavaCallback { progress ->
    trySend(progress)
  }

  close()
}

My CoroutineWorker, which displays the notification and downloads the file:

myFlow.collect { // update notification }
Result.Success()

My question is, how can I "throttle" the collection so that I for example collect 1%, but 1 second later it collects 5% and ignores all values between those two points

like image 621
Zun Avatar asked Oct 18 '25 08:10

Zun


1 Answers

fun <T> Flow<T>.throttleLatest(delayMillis: Long): Flow<T> = this
  .conflate()
  .transform {
    emit(it)
    delay(delayMillis)
  }

source: https://github.com/Kotlin/kotlinx.coroutines/issues/1446#issuecomment-1198103541

like image 84
Zun Avatar answered Oct 21 '25 01:10

Zun