美文网首页
Android Kotlin 实现网络请求嵌套回调

Android Kotlin 实现网络请求嵌套回调

作者: 咪神 | 来源:发表于2020-09-10 15:23 被阅读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)
            }
    

    运行结果:


    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

    相关文章

      网友评论

          本文标题:Android Kotlin 实现网络请求嵌套回调

          本文链接:https://www.haomeiwen.com/subject/ofepektx.html