rcd27
04/02/2022, 3:12 PMshareIn
functionality. Trying to share the flow emitions betwenn 3 subscribers, but only one of them (first) is collecting data:
@Test
fun testSharedFlowEmitions() = runBlocking {
var tick = 0
val f: Flow<Int> = flow {
while (tick < 10) {
emit(tick)
tick++
}
}
val sharedFlow: SharedFlow<Int> = f.shareIn(this, SharingStarted.Eagerly, replay = 1)
val firstSubscriber = sharedFlow.collect { Truth.assertThat(it).isGreaterThan(0) }
val secondSubscriber = sharedFlow.collect { Truth.assertThat(it).isGreaterThan(0) }
val thirdSubscriber = sharedFlow.collect { Truth.assertThat(it).isGreaterThan(0) }
}
Need help so that all three get ticks.collect
is a termination operator, changed all collect
to map
and then used:
combine(firstSubscriber, secondSubscriber, thirdSubscriber){_,_,_ -> Unit}.collect()
Works somehow, still not sure this is perfect solutionwasyl
04/02/2022, 4:21 PMlaunch
, or do onEach { }.launchIn(scope)
instead, that way the collections would happen in parallel (you can still lose some events though, since you’re starting the shared flow eagerly)