Skip to content

Instantly share code, notes, and snippets.

@Andrew0000
Created June 12, 2023 13:36
Show Gist options
  • Save Andrew0000/6d4477642cfadc7822742bd7986e79f4 to your computer and use it in GitHub Desktop.
Save Andrew0000/6d4477642cfadc7822742bd7986e79f4 to your computer and use it in GitHub Desktop.
throttleLatest
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