Hello, I got a `Flow` like ```flow { while (tr...
# coroutines
d
Hello, I got a
Flow
like
Copy code
flow {
    while (true) {
        emit(something)
        delay(interval)
    }
}.flowOn(injectedDispatcher)
In my test, I inject the dispatcher and test like
Copy code
val result = mutableListOf<Int>()
val interval = 30.seconds
val flow = getSavedCredentials(interval)
val job = launch {
    flow.toList(result)
}

repo.add(1)
advanceTimeBy(interval)

repo.add(2)
advanceTimeBy(interval)

repo.add(3)
advanceTimeBy(interval)
So I would expect
result
to be
[ 1 ], [ 1, 2 ], [ 1, 2, 3 ]
But instead it is
[ 1, 2, 3 ], [ 1, 2, 3 ], [ 1, 2, 3 ]
What’s wrong with it? 😵
g
try not exact number, 30 for flow, use a bit gap between, like advanceTimeBy(interval + 5.seconds)
d
Same 😞
g
could you provide a complete example on Kotlin Playground?
d
Sure, let me try to reproduce without dependants to project
Can I use coroutines-test on Playground?
🤔
May that help?
message has been deleted
g
Can I use coroutines-test on Playground? (edited)
Yes
d
How to? Deps are not resolved 😵
g
ahh, TestCoroutineDispatcher wouldn’t be available, indeed, worth to request adding it to Junit run configuration
d
So is there something I can do? 🙂
g
Yes
it’s because of closure of mutable property
Change
Copy code
emit(something)
With
Copy code
emit(something.toList())
What is happening, is that by time when flow lambda is invoking, repo alredy changed, essentially when you call
repo += 3
flow is not even dispatched, because it’s blocking code (mutating repo) but launch and flow are asyncronous
also, to make your test pass, swap emit and delay, otherwise flow will emit empty list
👍 1
d
Oh… This is tricky!! So that’s given by our mock! The signature of the method is
Map
, but our test implementation is a
MutableMap
under the hood!
Thank you!
also, to make your test pass, swap emit and delay, otherwise flow will emit empty list
Yup, noticed, May be better to delay the collecting