jeff
02/26/2021, 3:51 PM@Test
fun `emitting too fast`() {
val scope = CoroutineScope(Dispatchers.Default)
val actionFlow = MutableSharedFlow<String>(extraBufferCapacity = 10)
var success = false
actionFlow
.onEach { success = true }
.launchIn(scope) // 1
actionFlow.tryEmit("HELLO") // 2
runBlocking {
withTimeout(1000) {
while (!success) {
yield()
}
}
success shouldBe true
}
}
I understand why, I think, it's because the 'subscription' to actionFlow is launched (1
) and therefore hasn't happened yet by the time I try to emit (2
). Therefore, because `SharedFlow`s don't buffer or anything by default, the emission of "HELLO" is just dropped.
My question is, what's the best way to make sure 1
is ready before I do 2
. I can imagine there's a way to use SharedFlow.subscriptionCount
but that seems inelegant. Any better way?araqnid
02/26/2021, 4:11 PMaraqnid
02/26/2021, 4:12 PMval actionFlow = MutableSharedFlow<String>(extraBufferCapacity = 10)
var success = false
runBlocking {
val job = actionFlow
.onEach { success = true }
.launchIn(this) // 1
try {
yield()
actionFlow.tryEmit("HELLO") // 2
withTimeout(1000) {
while (!success) {
yield()
}
}
assertTrue(success)
} finally {
job.cancel()
}
}
jeff
02/26/2021, 4:13 PMjeff
02/26/2021, 4:14 PMaraqnid
02/26/2021, 4:14 PMjeff
02/26/2021, 4:16 PMjeff
02/26/2021, 4:22 PMjeff
02/26/2021, 4:33 PM@Test
fun `blank username`() {
val scope = CoroutineScope(Dispatchers.Default).childScope()
val actionFlow = MutableSharedFlow<String>(extraBufferCapacity = 10)
var success = false
actionFlow.onEach {
success = true
}
.launchIn(scope)
scope.launch {
yield()
actionFlow.tryEmit("HELLO")
}
runBlocking {
withTimeout(1000) {
while (!success) {
yield()
}
}
success shouldBe true
}
}
I think your version only works because the scope being passed to launchIn
is the one from runBlocking
which is using a single-threaded dispatcherjeff
02/26/2021, 4:38 PMwhile (actionFlow.subscriptionCount.value == 0) {}
around the yield. I still think there's probably a more elegant way, but this works for now. Thanks for your help!araqnid
02/26/2021, 5:04 PM