Skip to content

Instantly share code, notes, and snippets.

@JoseAlcerreca
Created May 18, 2021 14:48
Show Gist options
  • Save JoseAlcerreca/4aa7f688ff7b6c5e13ef958189041e06 to your computer and use it in GitHub Desktop.
Save JoseAlcerreca/4aa7f688ff7b6c5e13ef958189041e06 to your computer and use it in GitHub Desktop.
@Test
fun channelConflatedTest() {
val _channel = Channel<Int>(capacity = CONFLATED)
val exposedFlow: Flow<Int> = _channel.receiveAsFlow()
val testResults = mutableListOf<Int>()
val testResults2 = mutableListOf<Int>()
val testResults3 = mutableListOf<Int>()
runBlockingTest {
_channel.send(0) // This is lost
_channel.send(1) // This is lost
_channel.send(2) // This is sent to the only observer when it starts collecting
val observer1 = exposedFlow
val job1 = launch {
observer1.toList(testResults)
}
val observer2 = exposedFlow
val job2 = launch {
observer2.toList(testResults2)
}
_channel.send(3) // Sent while two observers are subscribed, but only one gets it
job1.cancel()
job2.cancel()
val observer3 = exposedFlow
val job3 = launch {
observer3.toList(testResults3)
}
_channel.send(4) // Sent to the only active observer (observer3)
job3.cancel()
// The first observer gets buffer + new updates
assertEquals(listOf(2, 3), testResults)
// Second observer gets nothing
assertEquals(listOf<Int>(), testResults2)
// Third observer gets new update
assertEquals(listOf(4), testResults3)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment