在Dispatcher.Main的上下文中执行网络任务 [英] Perform network task in context of Dispatcher.Main

查看:414
本文介绍了在Dispatcher.Main的上下文中执行网络任务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据帮助,应在Dispatcher.IO的上下文中执行长时间的网络任务.

according to help, long network tasks should be performed in the context of Dispatcher.IO.

但是为什么不能在Dispatcher.Main上下文中使用悬挂功能(如get)?线程本身没有被阻塞,所以我们期望代码不会出现任何问题吗?

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')
}

假设get是暂停功能,需要花费很多时间.

assuming get is suspend function taking much time.

谢谢.

推荐答案

您就在这里.您可以在Dispatchers.Main中提出该网络请求.

You are right here. You can make that network request in Dispatchers.Main.

这似乎是一个常见的误解,仅因为IO是由暂停功能执行的,所以您必须在Dispatchers.IO中调用它,这是不必要的(并且可能会很昂贵).

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).

按惯例,挂起函数不会阻塞调用线程,并且在需要时会在内部阻塞Dispatchers.IO.

suspending functions by convention don't block the calling thread and internally blocks in Dispatchers.IO if need be.

这篇关于在Dispatcher.Main的上下文中执行网络任务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆