Kotlin 协程

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

入门

//根据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()
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值