Created
July 31, 2020 02:26
-
-
Save bananaumai/f881e2fb48255ff73de56c8655e0f992 to your computer and use it in GitHub Desktop.
Throttling flow
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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