测试代码:
suspend fun login(): String {
Log.v("kotlinTest", "startLogin")
delay(3000)
val userId = "userId"
Log.v("kotlinTest", "endLogin")
return userId
}
suspend fun getUserInfo(userId: String): String {
Log.v("kotlinTest", "startGetUserInfo")
delay(1000)
val userInfo = "$userId UserInfo"
Log.v("kotlinTest", "endGetUserInfo")
return userInfo
}
GlobalScope.launch() {
Log.v("kotlinTest", "start")
val userId = login()
val userInfo = getUserInfo(userId)
Log.v("kotlinTest", userInfo)
}
运行结果:
![](https://img.haomeiwen.com/i3051422/0f0d7abf920e7317.png)
另一种方式
GlobalScope.launch {
async {
delay(3000)
Log.v("kotlinTest", "位置1 ${Thread.currentThread().name}")
}.await()
withContext(Dispatchers.Main) {
Log.v("kotlinTest", "位置2 ${Thread.currentThread().name}")
}
async {
delay(1000)
Log.v("kotlinTest", "位置3 ${Thread.currentThread().name}")
}.await()
Log.v("kotlinTest", "位置4 ${Thread.currentThread().name}")
withContext(Dispatchers.Main) {
Log.v("kotlinTest", "位置5 ${Thread.currentThread().name}")
}
}
运行效果:
![](https://img.haomeiwen.com/i3051422/a5f8122e736b2890.png)
网友评论