因此,我有一个以下函数,它使用 Ktor 客户端执行基本请求以获取用户列表,
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
}
}
}
现在,我使用它如下,
runBlocking {
val res = async {createRequest()}
val users = res.await()
Log.v("_APP_", users.toString())
}
但后来我读到runBlocking
应该用于测试和调试,不推荐用于生产。那我用什么代替runBlocking
呢?