-
Notifications
You must be signed in to change notification settings - Fork 1.9k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Flow size- and time-based chunked #2378
Open
circusmagnus
wants to merge
28
commits into
Kotlin:develop
Choose a base branch
from
circusmagnus:flow-time-based-chunked
base: develop
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
28 commits
Select commit
Hold shift + click to select a range
74d3d60
Merge pull request #1 from Kotlin/master
circusmagnus c0bf01b
Merge pull request #2 from Kotlin/develop
circusmagnus ccb76c8
Merge pull request #3 from Kotlin/master
circusmagnus d52fd69
Merge pull request #4 from Kotlin/master
circusmagnus 6fb01b9
Add time- and size-based chunking operators
circusmagnus 43bfcfb
Remove unused operators
circusmagnus c378678
Add visibility modifiers and clarify tests
circusmagnus cfbd8ea
Merge pull request #5 from Kotlin/master
circusmagnus 1c98a45
Merge remote-tracking branch 'origin/master' into flow-time-based-chu…
circusmagnus 5237f92
Chunk with interval and size only
circusmagnus 8b8b28e
Chunk with interval and size only - part 2
circusmagnus c2a4eac
Merge pull request #6 from Kotlin/master
circusmagnus 5c5c088
Add time- and size-based chunking operators
circusmagnus e04a106
Remove unused operators
circusmagnus 942b163
Add visibility modifiers and clarify tests
circusmagnus a12429e
Chunk with interval and size only
circusmagnus da1a57c
Chunk with interval and size only - part 2
circusmagnus 632d540
Prepare Chunking Methods
circusmagnus c3244ff
Add a bunch of tests
circusmagnus 5b5c3bd
Test Time based chunking
circusmagnus 2b9e5d1
Add docs and last tests
circusmagnus 9cb86f9
Add test for error propagation in Natural Chunking
circusmagnus d996a9b
Enable for JDK 1.6
circusmagnus b16e9b0
Merge remote-tracking branch 'origin/flow-time-based-chunked' into fl…
circusmagnus 3aaf7bd
Merge pull request #7 from Kotlin/develop
circusmagnus e795cc2
Merge remote-tracking branch 'origin/develop' into flow-time-based-ch…
circusmagnus 3fb6939
Adjust for changes in Channel API
circusmagnus 7431426
New Api dump
circusmagnus File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
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
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
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
211 changes: 211 additions & 0 deletions
211
kotlinx-coroutines-core/common/src/flow/operators/Chunk.kt
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,211 @@ | ||
/* | ||
* Copyright 2016-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license. | ||
*/ | ||
|
||
@file:JvmMultifileClass | ||
@file:JvmName("FlowKt") | ||
|
||
package kotlinx.coroutines.flow | ||
|
||
import kotlinx.coroutines.* | ||
import kotlinx.coroutines.channels.* | ||
import kotlinx.coroutines.flow.internal.* | ||
import kotlinx.coroutines.selects.* | ||
import kotlin.jvm.* | ||
|
||
/** | ||
* Groups emissions from this Flow into lists, according to the chosen ChunkingMethod. Time based implementations | ||
* collect upstream and emit to downstream in separate coroutines - concurrently, like Flow.buffer() operator. | ||
* Exact timing of emissions is not guaranteed, as it depends on collector coroutine availability. | ||
* | ||
* Size based chunking happens in a single coroutine and is purely sequential. | ||
* | ||
* Emissions always preserve order. | ||
* | ||
* It is possible to pass custom implementation of ChunkingMethod to chunked() operator. | ||
* | ||
* @param method Defines constrains on chunk size and time of its emission. | ||
*/ | ||
|
||
@ExperimentalCoroutinesApi | ||
public fun <T> Flow<T>.chunked(method: ChunkingMethod): Flow<List<T>> = with(method) { chunk() } | ||
|
||
@ExperimentalCoroutinesApi | ||
public interface ChunkingMethod { | ||
public fun <T> Flow<T>.chunk(): Flow<List<T>> | ||
|
||
public companion object { | ||
|
||
/** | ||
* Collects upstream and emits to downstream in separate coroutines - as soon as possible. If consumer keeps | ||
* up with the producer, it emits lists with single element. | ||
* | ||
* In case of slow consumer, it groups emissions into bigger lists. When consumer "speeds up", chunks | ||
* will get smaller. | ||
* | ||
* @param maxSize Maximum size of a single chunk. If reached, producer gets suspended until consumer "consumes" | ||
* a chunk. If maxSize is not specified, then chunk may grow indefinitely until jvm runs out of memory. | ||
*/ | ||
@Suppress("FunctionName") | ||
public fun Natural(maxSize: Int = Int.MAX_VALUE): ChunkingMethod = NaturalChunking(maxSize) | ||
|
||
/** | ||
* Collects upstream into a buffer and emits its content as a list at every interval. When upstream completes | ||
* (or is empty), it will try to emit immediately what is left of a chunk, omitting the interval. | ||
* | ||
* @param intervalMs Interval between emissions in milliseconds. Every emission happens only after | ||
* interval passes, unless upstream Flow completes sooner. | ||
* | ||
* @param maxSize Maximum size of a single chunk. If reached, producer gets suspended until consumer "consumes" | ||
* a chunk. If maxSize is not specified, then chunk may grow indefinitely until jvm runs out of memory. | ||
*/ | ||
@Suppress("FunctionName") | ||
public fun ByTime(intervalMs: Long, maxSize: Int = Int.MAX_VALUE): ChunkingMethod = | ||
TimeBased(intervalMs, maxSize) | ||
|
||
/** | ||
* Collects upstream into a buffer and emits its content as a list at every interval or when its buffer reaches | ||
* maximum size. When upstream completes (or is empty), it will try to emit immediately what is left of | ||
* a chunk, omitting the interval and maxSize constraints. | ||
* | ||
* @param intervalMs Interval between emissions in milliseconds. Every emission happens only after | ||
* interval passes, unless upstream Flow completes sooner or maximum size of a chunk is reached. | ||
* | ||
* @param maxSize Maximum size of a single chunk. If reached, it will try to emit a chunk, ignoring the | ||
* interval constraint. If so happens, time-to-next-chunk gets reset to the interval value. | ||
*/ | ||
@Suppress("FunctionName") | ||
public fun ByTimeOrSize(intervalMs: Long, maxSize: Int): ChunkingMethod = TimeOrSizeBased(intervalMs, maxSize) | ||
|
||
/** | ||
* Collects upstream into a buffer and emits its content as a list, when specified size is reached. | ||
* This implementation is purely sequential. If concurrent upstream collection and downstream emissions are | ||
* desired, one can use a buffer() operator after chunking | ||
* | ||
* @param size Exact size of emitted chunks. Only the last emission may be smaller. | ||
*/ | ||
@Suppress("FunctionName") | ||
public fun BySize(size: Int): ChunkingMethod = SizeBased(size) | ||
} | ||
} | ||
|
||
private class NaturalChunking(private val maxSize: Int) : ChunkingMethod { | ||
|
||
init { | ||
requirePositive(maxSize) | ||
} | ||
|
||
override fun <T> Flow<T>.chunk(): Flow<List<T>> = scopedFlow { downstream -> | ||
val upstream = buffer(maxSize).produceIn(this) | ||
|
||
while (!upstream.isClosedForReceive) { | ||
val chunk = upstream.awaitFirstAndDrain(maxSize) | ||
if (chunk.isNotEmpty()) downstream.emit(chunk) | ||
} | ||
} | ||
} | ||
|
||
private class TimeBased(private val intervalMs: Long, private val maxSize: Int) : ChunkingMethod { | ||
|
||
init { | ||
requirePositive(intervalMs) | ||
requirePositive(maxSize) | ||
} | ||
|
||
override fun <T> Flow<T>.chunk(): Flow<List<T>> = scopedFlow { downstream -> | ||
val upstreamCollection = Job() | ||
val upstream = produce<T>(capacity = maxSize) { | ||
collect { element -> channel.send(element) } | ||
upstreamCollection.complete() | ||
} | ||
|
||
whileSelect { | ||
upstreamCollection.onJoin { | ||
val chunk = upstream.drain(maxElements = maxSize) | ||
if (chunk.isNotEmpty()) downstream.emit(chunk) | ||
false | ||
} | ||
|
||
onTimeout(intervalMs) { | ||
val chunk = upstream.drain(maxElements = maxSize) | ||
if (chunk.isNotEmpty()) downstream.emit(chunk) | ||
true | ||
} | ||
} | ||
} | ||
} | ||
|
||
private class SizeBased(private val size: Int) : ChunkingMethod { | ||
|
||
init { | ||
requirePositive(size) | ||
} | ||
|
||
override fun <T> Flow<T>.chunk(): Flow<List<T>> = flow { | ||
val accumulator = ArrayList<T>(size) | ||
collect { element -> | ||
accumulator.add(element) | ||
if (accumulator.size == size) emit(accumulator.drain()) | ||
} | ||
if (accumulator.isNotEmpty()) emit(accumulator) | ||
} | ||
} | ||
|
||
private class TimeOrSizeBased(private val intervalMs: Long, private val maxSize: Int) : ChunkingMethod { | ||
|
||
init { | ||
requirePositive(intervalMs) | ||
requirePositive(maxSize) | ||
} | ||
|
||
override fun <T> Flow<T>.chunk(): Flow<List<T>> = scopedFlow { downstream -> | ||
val emitNowAndMaybeContinue = Channel<Boolean>(capacity = Channel.RENDEZVOUS) | ||
val elements = produce<T>(capacity = maxSize) { | ||
collect { element -> | ||
val hasCapacity = channel.trySend(element).isSuccess | ||
if (!hasCapacity) { | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. what do you think about size instead of maxSize like SizedBased? when channel reached to size it should be emit |
||
emitNowAndMaybeContinue.send(true) | ||
channel.send(element) | ||
} | ||
} | ||
emitNowAndMaybeContinue.send(false) | ||
} | ||
|
||
whileSelect { | ||
emitNowAndMaybeContinue.onReceive { shouldContinue -> | ||
val chunk = elements.drain(maxElements = maxSize) | ||
if (chunk.isNotEmpty()) downstream.emit(chunk) | ||
shouldContinue | ||
} | ||
|
||
onTimeout(intervalMs) { | ||
val chunk = elements.drain(maxElements = maxSize) | ||
if (chunk.isNotEmpty()) downstream.emit(chunk) | ||
true | ||
} | ||
} | ||
} | ||
|
||
} | ||
|
||
private suspend fun <T> ReceiveChannel<T>.awaitFirstAndDrain(maxElements: Int): List<T> = try { | ||
val first = receive() | ||
drain(mutableListOf(first), maxElements) | ||
} catch (e: ClosedReceiveChannelException) { | ||
emptyList() | ||
} | ||
|
||
|
||
private tailrec fun <T> ReceiveChannel<T>.drain(acc: MutableList<T> = mutableListOf(), maxElements: Int): List<T> = | ||
if (acc.size == maxElements) acc | ||
else { | ||
val nextValue = tryReceive().getOrElse { error: Throwable? -> error?.let { throw(it) } ?: return acc } | ||
acc.add(nextValue) | ||
drain(acc, maxElements) | ||
} | ||
|
||
private fun <T> MutableList<T>.drain() = toList().also { this.clear() } | ||
|
||
private fun requirePositive(size: Int) = require(size > 0) | ||
|
||
private fun requirePositive(intervalMs: Long) = require(intervalMs > 0) |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This file has been apparently changed on master but not on develop - with PR: Improve readability. #2563