-
-
Save morristech/0786b3e862e76ad110fbcd35506ae1c7 to your computer and use it in GitHub Desktop.
timedBuffer
This file contains hidden or 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.* | |
| import kotlinx.coroutines.flow.* | |
| private class Buffer<T> { | |
| private val list = arrayListOf<T>() | |
| @Synchronized | |
| fun add(value: T) { list.add(value) } | |
| @Synchronized | |
| fun pollIfNotEmpty() = | |
| list.takeIf { it.isNotEmpty() }?.toList()?.also { list.clear() } | |
| } | |
| fun <T> Flow<T>.timedBuffer(millis: Long): Flow<List<T>> = channelFlow { | |
| val buffer = Buffer<T>() | |
| suspend fun flush() { buffer.pollIfNotEmpty()?.let { send(it) } } | |
| val job = launch { | |
| while (isActive) { | |
| delay(millis) | |
| flush() | |
| } | |
| } | |
| collect { buffer.add(it) } | |
| job.cancelAndJoin() | |
| flush() | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment