入门
//根据subCode获取响应的项目应用信息
@GET(UrlConstants.getSubCommunityInfoByCode)
Call<SimpleResp<IconBean>> getSubCommunityInfoByCode(@Query("subCode") String subCode);
AdvancedRetrofitHelper.enqueue(context, mServiceApi.getSubCommunityInfoByCode(subCode), new SimpleRetrofitCallback<SimpleResp<IconBean>>() {
@Override
public void onSuccess(Call<SimpleResp<IconBean>> call, SimpleResp<IconBean> resp) {
super.onSuccess(call, resp);
...
showUserUI(resp.data);
...
}
});
implementation '...retrofit:2.6+'
@GET(UrlConstants.getSubCommunityInfoByCode)
suspend fun getSubCommunityInfoByCode(@Query("subCode") orgId: subCode): SimpleResp<IconBean>
GlobalScope.launch(Dispatchers.Main) {
showUserUI(mServiceApi.getSubCommunityInfoByCode("subCode"))
}
通过协程的写法,整个流程就看起来就像一套同步的代码
[曾经JakeWharton kotlin coroutines的远程库,现已废弃](https://github.com/JakeWharton/retrofit2-kotlin-coroutines-adapter)
showUserUI(mServiceApi.getSubCommunityInfoByCode("subCode").await())
//注意以下不是正确的代码,仅供大家理解协程使用
GlobalScope.launch(Dispatchers.Main) {
mServiceApi.getSubCommunityInfoByCode("subCode").await(object: Continuation<IconBean>{
override fun resume(value: IconBean) {
showUserUI(value)
}
override fun resumeWithException(exception: Throwable){
showError(exception)
}
})
}
从执行机制上来讲,协程跟回调没有什么本质的区别
启动
val thread = object : Thread(){
override fun run() {
super.run()
//do what you want to do.
}
}
thread.start()
val myThread = thread {
//do what you want
}
协程的写法就像线程
GlobalScope.launch {
//do what you want
}
启动协程需要三样东西,分别是 上下文、启动模式、协程体,协程体
异常处理
GlobalScope.launch(Dispatchers.Main) {
try {
showUserUI(mServiceApi.getSubCommunityInfoByCode("subCode"))
} catch (e: Exception) {
showError(e)
}
}
协程onError的处理也非常像同步代码,由于协程的框架层级的,实现后比RxJava更加易懂
getUserObservable()
.observeOn(AndroidSchedulers.mainThread())
.subscribe ({ user ->
userNameView.text = user.name
}, {
userNameView.text = "Get User Error: $it"
})
Android
val mainScope = MainScope()
launchButton.setOnClickListener {
mainScope.launch {
log(1)
textView.text = async(Dispatchers.IO) {
log(2)
delay(1000)
log(3)
"Hello1111"
}.await()
log(4)
}
}
public fun MainScope(): CoroutineScope = ContextScope(SupervisorJob() + Dispatchers.Main)
abstract class ScopedActivity: Activity(), CoroutineScope by MainScope(){
override fun onDestroy() {
super.onDestroy()
cancel()
}
}

本文深入探讨了如何在Android开发中利用Kotlin协程与Retrofit库进行高效的数据请求处理,展示了协程如何简化异步操作,使其更接近于同步代码的编写方式,同时提供了错误处理的最佳实践。
6323

被折叠的 条评论
为什么被折叠?



