return original Flow if throttle timeout is negative or zero, similar to delay

GitOrigin-RevId: 1f0514b3a2da1deb6b7c977e3fb218b5bb4d179d
This commit is contained in:
Daniil Ovchinnikov
2022-01-20 19:16:24 +03:00
committed by intellij-monorepo-bot
parent d5c74bb7a5
commit e31bd70aa9

View File

@@ -31,23 +31,28 @@ import kotlinx.coroutines.launch
* 1, 3, 4
* ```
*/
fun <X> Flow<X>.throttle(timeMs: Long): Flow<X> = channelFlow {
val latch = Channel<Unit>()
val latchJob = launch(start = CoroutineStart.UNDISPATCHED) {
while (isActive) {
latch.send(Unit)
delay(timeMs)
}
fun <X> Flow<X>.throttle(timeMs: Long): Flow<X> {
if (timeMs <= 0) {
return this
}
try {
collectLatest {
latch.receive()
@Suppress("EXPERIMENTAL_API_USAGE")
send(it)
return channelFlow {
val latch = Channel<Unit>()
val latchJob = launch(start = CoroutineStart.UNDISPATCHED) {
while (isActive) {
latch.send(Unit)
delay(timeMs)
}
}
try {
collectLatest {
latch.receive()
@Suppress("EXPERIMENTAL_API_USAGE")
send(it)
}
}
finally {
latchJob.cancel()
latch.close()
}
}
finally {
latchJob.cancel()
latch.close()
}
}