I need to unit-test the code involving a `scan` op...
# coroutines
d
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
As I can see, you're sending only one element (42)
d
Yep, the first one is an initial accumulator of scan:
scan(1) {...}
, it will be emitted right away.