https://kotlinlang.org logo
Title
b

bitkid

02/01/2018, 12:24 PM
how would i write a unit test for that? because as soon as i run this in runBlocking{} in the test doSomething() will be called on the same thread.
e

elizarov

02/01/2018, 12:32 PM
It will not be called in the same thread in test. By default,
async { ... }
uses
CommonPool
dispatcher and
doSomething
will be executed in that another thread.
c

christophsturm

02/01/2018, 1:01 PM
but we actually want it running in the same thread. can i tell async that it should use the same thread?
it will still be async because the method that we call is a non blocking suspend method
e

elizarov

02/01/2018, 1:02 PM
You can specify the context for async explicitly if you need it.
async(ctx) { ... }
c

christophsturm

02/01/2018, 1:05 PM
ok so just use unconfined to run it in the same thread?
e

elizarov

02/01/2018, 1:06 PM
Unconfined
runs in the same thread only until the first suspension point.
If you actually want the same thread, then from inside
runBlocking
you should be passing
coroutineContext
.
c

christophsturm

02/01/2018, 1:07 PM
runBlocking is just what we use in the test suite
e

elizarov

02/01/2018, 1:08 PM
So, if you want it to run in `UI' thread in production, then you use
async(UI) { … }
and for tests you make UI injectable and use
coroutineContext
that’s available inside
runBlocking