Skip to content

Instantly share code, notes, and snippets.

@JoseAlcerreca
Created May 18, 2021 14:58
Show Gist options
  • Save JoseAlcerreca/a371be28293336934cb90ec49b42fd63 to your computer and use it in GitHub Desktop.
Save JoseAlcerreca/a371be28293336934cb90ec49b42fd63 to your computer and use it in GitHub Desktop.
@Test
fun channelShareInTest() {
val scope = TestCoroutineScope()
val _channel = Channel<Int>(capacity = 2, onBufferOverflow = BufferOverflow.DROP_OLDEST)
val exposedFlow: SharedFlow<Int> = _channel
.consumeAsFlow().shareIn(scope, SharingStarted.WhileSubscribed())
val testResults = mutableListOf<Int>()
val testResults2 = mutableListOf<Int>()
runBlockingTest {
_channel.send(0)
_channel.send(1)
_channel.send(2)
val observer1 = exposedFlow
val job1 = launch {
observer1.toList(testResults)
}
val observer2 = exposedFlow
val job2 = launch {
observer2.toList(testResults2)
}
_channel.send(3)
job1.cancel()
job2.cancel()
// The first observer gets buffer + new updates
assertEquals(listOf(1, 2, 3), testResults)
// Second observer only gets new updates
assertEquals(listOf(3), testResults2)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment