https://kotlinlang.org logo
#coroutines
Title
# coroutines
d

dimsuz

07/05/2020, 9:04 PM
I need to unit-test the code involving a
scan
operator and hot event stream. Basically I want to configure the flow, send events and verify they are received:
Copy code
runBlocking(Dispatchers.Default) {
    val events = BroadcastChannel<Int>(capacity = Channel.BUFFERED)
    launch {
      events.asFlow().scan(1) { accumulator, value -> value }
        .take(2)
        .collect { println("received $it") }
    }
    launch {
      events.send(42)
    }
  }
The above doesn't work, it receives 1(inital accum) item and then hangs indefinitely, because
send
is done before collect begins. I tried moving
send
inside the
collect
, after initial element is received, but this doesn't work, because
scan
is implemented so that its internal
collect
also starts after my
send
is called (it starts after first collection completes). Any advice on how to do that?
i

ildar.i [Android]

07/06/2020, 4:18 AM
As I can see, you're sending only one element (42)
d

dimsuz

07/06/2020, 9:16 AM
Yep, the first one is an initial accumulator of scan:
scan(1) {...}
, it will be emitted right away.
2 Views