如何使用 Kotlin 协程正确执行 http 请求?

问题描述

因此,我有以下函数,它使用 Ktor 客户端执行基本请求以获取用户列表,

@H_404_2@suspend fun createRequest(): List<User>? { return withContext(dispatchers.IO) { try { val client = HttpClient(CIO) val response: HttpResponse = client.get("http://10.0.2.2:9999/users") client.close() val str = response.readText() val itemType = object : Typetoken<List<User>>() {}.type Gson().fromJson<List<User>>(str,itemType) } catch (e: Exception) { null } } }

现在,我使用它如下,

@H_404_2@runBlocking { val res = async {createRequest()} val users = res.await() Log.v("_APP_",users.toString()) }

但后来我读到 runBlocking 应该用于测试和调试,不推荐用于生产。那么我用什么来代替 runBlocking

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)