android - Kotlin 协程不等待网络结果返回
问题描述
我正在尝试从 Kotlin 中的服务器获取一些数据,我希望在这些数据上做一些进一步的处理,比如向用户显示它。但是执行不是等待/阻塞结果返回,而是继续执行。
这是代码:
class UserLand : AppCompatActivity() {
class SyncViewModel(): ViewModel() {
suspend fun startingSync(accesstoken: String): String {
var response = ""
viewModelScope.launch(Dispatchers.IO) {
val reqParam = "token=$accesstoken"
val mURL = URL("<-- server end point here -->")
with(mURL.openConnection() as HttpURLConnection) {
// optional default is GET
requestMethod = "POST"
val wr = OutputStreamWriter(outputStream);
wr.write(reqParam);
wr.flush();
println("2 : $url")
println("3 : $responseCode")
BufferedReader(InputStreamReader(inputStream)).use {
var inputLine = it.readLine()
while (inputLine != null) {
response += inputLine
inputLine = it.readLine()
}
Log.d("4: ","Response : $response")
}
}
}
Log.d("5", response)
return response
}
}
fun syncWithServer(view: View) {
val accesstoken = "johndoe"
var response = ""
if (accesstoken != null) {
Log.d("----->", "1")
runBlocking {
response = SyncViewModel().startingSync(accesstoken)
Log.d("----->", "6")
}
}
//
Log.d("Final result: 7:---------> ", response)
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_snyc_packages_with_server)
}
}
我syncWithServer()
通过点击屏幕上的按钮进行呼叫。在此之后,syncWithServer()
将在函数中的单独线程上启动网络请求startingSync()
。现在我瞄准的日志的执行顺序如下:
1->2->3->4->5->6->7(根据日志和打印信息)。最后,在 log(7) 处,我将从服务器获得我想要进一步处理的响应。但实际执行结果如下:
1->6->2->3->4。注意 5 和 7 没有登录到 android logcats。我相信执行线程没有等待网络请求结果返回,因此没有达到理想的执行步骤。
我刚开始使用 kotlin 中的协同程序。我知道我遗漏了一些东西,但它到底是什么?
解决方案
viewModelScope.launch(Dispatchers.IO)
在您的代码中创建并行工作,您有 2 个变体来修复它:
1 - 而不是viewModelScope.launch(Dispatchers.IO)
使用withContenxt(Dispatchers.IO)
只会改变dispathers
2 - 通过调用此块的结尾而不是viewModelScope.launch(Dispatchers.IO)
使用viewModelScope.async(Dispatchers.IO)
并等待它的结果.await()
推荐阅读
- python - 最有影响力的词中出现的停用词
- nsis - 我对 ReadINIStr 的第二次调用有什么问题?
- python - 我想创建多个(即大约 4 个)开/关切换按钮
- twilio - 配置 FindMe/Hunt 功能
- excel - Selenium Webdrive (VBA) - 查找元素的属性,其中有相同名称的重复属性
- python - 如何在没有正则表达式的情况下实现过滤 IPv4 地址的算法?
- python - 无法挖掘位于链接按钮下的某些信息
- google-sheets - 带有日期条件的 Google 表格 Sumifs
- html - 输入日期值属性django
- bash - 如何让您的 .bashrc 文件在第一个错误时退出而不将 errexit 标志继承到交互式 shell 中?