Skip to content

Instantly share code, notes, and snippets.

@PatilShreyas
Last active October 22, 2023 07:19
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 PatilShreyas/5678e6ab24715b1ff1dc6544af5dc008 to your computer and use it in GitHub Desktop.
Save PatilShreyas/5678e6ab24715b1ff1dc6544af5dc008 to your computer and use it in GitHub Desktop.
suspend fun collect(collector: FlowCollector<List<T>>) = coroutineScope<Unit> {
+ val mutex = Mutex()
// For storing un-emitted values
val values = mutableListOf<T>()
// Continue looping after intervals `duration` and emit the items in the collector
// and clear the existing items from the `values`.
launch {
while (true) {
delay(duration)
+ mutex.withLock {
// If the upstream flow has been completed and there are no values
// pending to emit in the collector, just break this loop.
+ if (isFlowCompleted && values.isEmpty()) {
+ return@launch
+ }
+ collector.emit(values.toList())
+ values.clear()
+ }
}
}
// Collect the upstream flow and add the items to the above `values` list
upstream.collect {
+ mutex.withLock {
+ values.add(it)
+ }
}
isFlowCompleted = true
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment