[英]Kotlin Coroutine not waiting for the network result to return
我正在嘗試從 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)
只會改變withContenxt(Dispatchers.IO)
員
2 - 而不是viewModelScope.launch(Dispatchers.IO)
使用viewModelScope.async(Dispatchers.IO)
並通過調用此塊的.await()
結束等待它的結果
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.