According to a recent article on /r/AndroidDev by ...
# coroutines
a
According to a recent article on /r/AndroidDev by Sean McQuillan, all suspending functions should be main safe and use
withContext(...)
depending on what they’re doing. If
withContext(<http://Dispatchers.IO|Dispatchers.IO>)
always runs on a background thread, how can we ensure single threading for testing purposes? Even
runBlocking()
doesn’t affect this.
or the non-deprecated option:
Executors.newSingleThreadExecutor().asCoroutineDispatcher()
s
"Main safe"? If you mean "thread safe": whatever dispatcher is used, local state captured by the coroutine is thread safe; each statement executed in order, one after each other, never at the same time, even if they are executed on different threads. This is not true for state that is global or not local to the coroutine.
a
@pakoito That makes sense. So if I wanted my tests to be synchronous, I would have a
ThreadFactory
that just returns the current thread, then set that on a
ThreadPoolExecutor
. Afterwards I would convert that into a
Dispatcher
and provide that whenever launching a new coroutine in a test
Or I could avoid hardcoding dispatchers in my code and use dependency injection to specify dispatchers
👍 1
🔝 5
g
Usually it shouldn't be a problem, you should test mostly suspend functions, so multithreading is not a problem in this case, and for some integration tests inject Scope/Dispatcher