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

测试代码:

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
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。