Created
June 12, 2023 13:36
-
-
Save Andrew0000/6d4477642cfadc7822742bd7986e79f4 to your computer and use it in GitHub Desktop.
throttleLatest
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
fun <T> Flow<T>.throttleLatest(delayMillis: Long) = this | |
.conflate() | |
.transform { | |
emit(it) | |
delay(delayMillis) | |
} | |
import kotlinx.coroutines.ExperimentalCoroutinesApi | |
import kotlinx.coroutines.delay | |
import kotlinx.coroutines.flow.flow | |
import kotlinx.coroutines.flow.toList | |
import kotlinx.coroutines.test.runTest | |
import org.junit.Assert.assertEquals | |
import org.junit.Test | |
class FlowThrottleTest { | |
@Test | |
@OptIn(ExperimentalCoroutinesApi::class) | |
fun test_throttleLatest() = runTest { | |
val flow = flow { | |
for (i in 1..32) { | |
delay(100) | |
emit(i) | |
} | |
} | |
val result = flow.throttleLatest(1000).toList() | |
assertEquals(listOf(1, 10, 20, 30, 32), result) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment