//Thread
thread {
//network request
getComment()
}
//Java Executors
Executors.newCachedThreadPool().execute {
//network request
getComment()
}
private fun getComment() {
apiClient.getComment("example post id")?.enqueue(object : Callback<CommentModel> {
override fun onResponse(call: Call<CommentModel>, response: Response<CommentModel>) {
//将请求到的数据显示到TextView上
textView.text = response.body().toString()
}
override fun onFailure(call: Call<CommentModel>, t: Throwable) {
//将错误信息显示到TextView上
textView.text = "network error"
}
})
}
//Kotlin Coroutines
//Dispatcher.IO 指定协程运行在用来执行磁盘或网络I/O的调度器中
lifecycleScope.launch(Dispatchers.IO) {
getComment()
}
private suspend fun getComment() {
val apiClient = CommentApiClient()
try {
val comment = apiClient.getComment("example post id")
withContext(Dispatchers.Main) { //切换到主线程
textView.text = comment?.body //请求成功
}
} catch (e: NetworkErrorException) {
textView.text = "network error" //请求失败
}
}
可能我们会这样写,请求UserInfo返回结果后,在onResponse回调中再请求Comment,然后在getComment的onResponse方法中更新UI,标准的嵌套地狱。不过,这仅仅是2个请求串行,如果是5个…10个…
//先请求UserInfo
apiClient.getUserInfo()?.enqueue(object : Callback<UserInfo> {
override fun onResponse(call: Call<UserInfo>, response: Response<UserInfo>) {
//处理UserInfo
...
//使用用户id作为参数,仔请求获取Comment
apiClient.getComment(info.userId)?.enqueue(object : Callback<CommentModel> {
override fun onResponse(call: Call<CommentModel>, response: Response<CommentModel>) {
//将请求到Comment的数据显示到TextView上
textView.text = response.body().toString()
...
}
//请求用户信息
val userInfo = apiClient.getUserInfo()
//使用用户信息中的id作为参数,请求用户评论
val comment = apiClient.getComment(userInfo.userId)
withContext(Dispatchers.Main) { //切换到主线程
textView.text = comment?.body //请求成功
}
如果有一个业务场景,需要我们请求用户个人信息和用户头像,然后将请求到的两个结果在同一时间展示出来,要怎么做?我们可能想到直接请求两个接口,然后再把两个请求的结果进行融合。
//请求用户昵称
val userName = apiClient.getUserName()
//请求用户头像
val userAvatar = apiClient.getUserAvatar()
//切换到主线程
withContext(Dispatchers.Main) {
//请求成功
updateUI(userName.await(),userAvatar.await())
}