Skip to content

Instantly share code, notes, and snippets.

@bananaumai
Created July 31, 2020 02:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bananaumai/f881e2fb48255ff73de56c8655e0f992 to your computer and use it in GitHub Desktop.
Save bananaumai/f881e2fb48255ff73de56c8655e0f992 to your computer and use it in GitHub Desktop.
Throttling flow
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.flow.flow
fun <T> Flow<T>.throttleByTime(wait: Long): Flow<List<T>> = flow {
val holder = emptyList<T>().toMutableList()
var nextTime = 0L
collect {
val curTime = System.currentTimeMillis()
holder.add(it)
if (curTime >= nextTime) {
emit(holder.toList())
nextTime = curTime + wait
holder.clear()
}
}
}
fun <T> Flow<T>.throttleByCount(limit: Long): Flow<List<T>> = flow {
val holder = emptyList<T>().toMutableList()
var count = 0
collect {
count++
holder.add(it)
if (count >= limit) {
emit(holder.toList())
count = 0
holder.clear()
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment