Tunji Dahunsi
09/09/2024, 9:17 PM@Test
fun hmm2() = runTest {
val channel = Channel<Int>()
val shared = channel.consumeAsFlow()
.onCompletion { println("CANCELLED") }
.shareIn(this, SharingStarted.WhileSubscribed())
val j = launch(UnconfinedTestDispatcher()) {
shared.collect {
println("$it in first")
}
}
channel.send(1)
channel.send(2)
advanceUntilIdle()
val j2 = launch(UnconfinedTestDispatcher()) {
shared.collect {
println("$it in second")
}
}
channel.send(3)
advanceUntilIdle()
j.cancel()
channel.send(4)
j2.cancel()
}
Tunji Dahunsi
09/09/2024, 9:19 PMchannel.send(4)
suspends indefinitely as the upstream has been cancelled despite j2 not being cancelledTunji Dahunsi
09/09/2024, 9:21 PMMutableSharedFlow
, however it is for any SharedFlow
created with sharedIn
Dmitry Khalanskiy [JB]
09/10/2024, 8:24 AMAre you sure that's what happens? When I try running your code and addsuspends indefinitelychannel.send(4)
println("Sent 4")
after channel.send(4)
, the line gets printed.
Unless you're doingCopy codelaunch(UnconfinedTestDispatcher())
Dispatchers.setMain
, this line is incorrect: UnconfinedTestDispatcher
must be given the testScheduler
used by runTest
. Dispatchers.setMain
automatically propagates its scheduler to the newly-created dispatchers.Dmitry Khalanskiy [JB]
09/10/2024, 8:25 AM@Test
fun hmm2() = runTest {
val channel = Channel<Int>()
val shared = channel.consumeAsFlow()
.onCompletion { println("CANCELLED") }
.shareIn(backgroundScope, SharingStarted.WhileSubscribed())
val j = launch(UnconfinedTestDispatcher(testScheduler)) {
shared.collect {
println("$it in first")
}
}
channel.send(1)
channel.send(2)
advanceUntilIdle()
val j2 = launch(UnconfinedTestDispatcher(testScheduler)) {
shared.collect {
println("$it in second")
}
}
channel.send(3)
advanceUntilIdle()
j.cancel()
println("Sending 4")
channel.send(4)
println("Sent 4")
j2.cancel()
}
Note the backgroundScope
(which ensures that the coroutine created by consumeAsFlow
gets cancelled when the test finishes).Tunji Dahunsi
09/10/2024, 2:44 PMbackgroundScope
, thank you!