Perform network task in context of Dispatcher.Main

社会主义新天地 提交于 2020-06-16 17:25:23

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!