https://kotlinlang.org logo
#flow
Title
# flow
r

rcd27

04/02/2022, 3:12 PM
Greetings, seems like I misunderstand
shareIn
functionality. Trying to share the flow emitions betwenn 3 subscribers, but only one of them (first) is collecting data:
Copy code
@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.
Came to idea that
collect
is a termination operator, changed all
collect
to
map
and then used:
Copy code
combine(firstSubscriber, secondSubscriber, thirdSubscriber){_,_,_ -> Unit}.collect()
Works somehow, still not sure this is perfect solution
w

wasyl

04/02/2022, 4:21 PM
you can collect in a
launch
, 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)
1
3 Views