Android Kotlin 实现网络请求嵌套回调
2020-09-10 本文已影响0人
咪神
测试代码:
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)
}
运行结果:

另一种方式
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}")
}
}
运行效果:
