测试代码:
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)
}
运行结果:
QQ截图20200910152218.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}")
}
}
运行效果:
QQ截图20200910173043.png
网友评论