Skip to content

Optimize debounce operator allocation pressure by using conflated pro… #1415

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

Merged
merged 1 commit into from
Aug 9, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -14,3 +14,11 @@ import kotlin.jvm.*
@JvmField
@SharedImmutable
internal val NULL = Symbol("NULL")

/*
* Symbol used to indicate that the flow is complete.
* It should never leak to the outside world.
*/
@JvmField
@SharedImmutable
internal val DONE = Symbol("DONE")
33 changes: 14 additions & 19 deletions kotlinx-coroutines-core/common/src/flow/operators/Delay.kt
Original file line number Diff line number Diff line change
Expand Up @@ -62,18 +62,21 @@ public fun <T> Flow<T>.delayEach(timeMillis: Long): Flow<T> = flow {
public fun <T> Flow<T>.debounce(timeoutMillis: Long): Flow<T> {
require(timeoutMillis > 0) { "Debounce timeout should be positive" }
return scopedFlow { downstream ->
val values = Channel<Any?>(Channel.CONFLATED) // Actually Any, KT-30796
// Channel is not closed deliberately as there is no close with value
val collector = async {
collect { value -> values.send(value ?: NULL) }
// Actually Any, KT-30796
val values = produce<Any?>(capacity = Channel.CONFLATED) {
collect { value -> send(value ?: NULL) }
}

var isDone = false
var lastValue: Any? = null
while (!isDone) {
while (lastValue !== DONE) {
select<Unit> {
values.onReceive {
lastValue = it
// Should be receiveOrClosed when boxing issues are fixed
values.onReceiveOrNull {
if (it == null) {
if (lastValue != null) downstream.emit(NULL.unbox(lastValue))
lastValue = DONE
} else {
lastValue = it
}
}

lastValue?.let { value ->
Expand All @@ -83,12 +86,6 @@ public fun <T> Flow<T>.debounce(timeoutMillis: Long): Flow<T> {
downstream.emit(NULL.unbox(value))
}
}

// Close with value 'idiom'
collector.onAwait {
if (lastValue != null) downstream.emit(NULL.unbox(lastValue))
isDone = true
}
}
}
}
Expand Down Expand Up @@ -118,16 +115,14 @@ public fun <T> Flow<T>.sample(periodMillis: Long): Flow<T> {
// Actually Any, KT-30796
collect { value -> send(value ?: NULL) }
}

var isDone = false
var lastValue: Any? = null
val ticker = fixedPeriodTicker(periodMillis)
while (!isDone) {
while (lastValue !== DONE) {
select<Unit> {
values.onReceiveOrNull {
if (it == null) {
ticker.cancel(ChildCancelledException())
isDone = true
lastValue = DONE
} else {
lastValue = it
}
Expand Down