client uses Retrofit Coroutines Adapter.
I don't understand, why am I not getting NetworkOnMainThreadException??
Is't it called on the main thread??
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val deferred = client.getStuffDeferred(file)
CoroutineScope(Dispatchers.Main).launch {
val response = deferred.await()
}
}
If you pass Coroutine Context to your coroutine builder, then such coroutine will use that thread to execution.
I.e.
newSingleThreadContext and newFixedThreadPoolContext.Executor can be converted to dispatcher with asCoroutineDispatcher extension function.So, use like :
CoroutineScope(Dispatchers.IO).launch { // we should use IO thread here !
}
if you call launch on the Dispatchers.Main it does run on the main thread but suspends the execution so as to not block the thread.
So That this behavior does not block or throw NetworkOnMainThreadException because there is not suspending methods or runBlocking method in your CoroutineScope
But: you should change your context during making a network operation or any heavy operation with may slow down your UI thread operation by using
withContext(Dispatchers.IO){// your suspended calls}
which allows you to change your current context to the background thread and continue your work in the main thread without any problem
Take a look into this article on solution3 which use Coroutine