问题
according to help, long network tasks should be performed in the context of Dispatcher.IO.
But why couldn't use suspend function like get in Dispatcher.Main context? Thread itself isn't blocked, so do we expect any problem from code like:
GlobalScope.launch(Dispatchers.Main) {
val client = HttpClient(Android)
var data: String = client.get('http://example.com')
}
assuming get
is suspend function taking much time.
Thanks.
回答1:
You are right here. You can make that network request in Dispatchers.Main
.
It seems to be a common misconception, that just because IO is being performed by a suspend function, you must call it in Dispatchers.IO
, which is unnecessary (and can be expensive).
suspending functions by convention don't block the calling thread and internally blocks in Dispatchers.IO
if need be.
来源:https://stackoverflow.com/questions/62180453/perform-network-task-in-context-of-dispatcher-main