首页 > 解决方案 > 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 中的协同程序。我知道我遗漏了一些东西,但它到底是什么?

标签: androidkotlinkotlin-coroutines

解决方案


viewModelScope.launch(Dispatchers.IO)在您的代码中创建并行工作,您有 2 个变体来修复它:

1 - 而不是viewModelScope.launch(Dispatchers.IO)使用withContenxt(Dispatchers.IO)只会改变dispathers

2 - 通过调用此块的结尾而不是viewModelScope.launch(Dispatchers.IO)使用viewModelScope.async(Dispatchers.IO)并等待它的结果.await()


推荐阅读