Created
May 18, 2021 14:48
-
-
Save JoseAlcerreca/4aa7f688ff7b6c5e13ef958189041e06 to your computer and use it in GitHub Desktop.
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
@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