Kotlin协程介绍(四)创建协程 async/await

Kotlin协程介绍(四)创建协程 launch中介绍了可以使用launch创建并启动一个协程,除此之外还可以通过async创建并启动一个协程:

public fun <T> CoroutineScope.async(
    context: CoroutineContext = EmptyCoroutineContext,
    start: CoroutineStart = CoroutineStart.DEFAULT,
    block: suspend CoroutineScope.() -> T
): Deferred<T> {
    val newContext = newCoroutineContext(context)
    val coroutine = if (start.isLazy)
        LazyDeferredCoroutine(newContext, block) else
        DeferredCoroutine<T>(newContext, active = true)
    coroutine.start(start, coroutine, block)
    return coroutine
}

async的函数签名和几乎完全相同,同样是CoroutineScope的一个扩展函数,用于开启一个新的子协程,与 launch 函数一样可以设置启动模式,不同的是它的返回值为 Deferred,Deferred是Job的子类,但是通过Deferred.await()可以得到一个返回值,简单理解的话,这就是一个带返回值的 launch 函数

data class Profile(val name: String = "Jack")

//heavy work
fun loadProfile(): Profile {                                
    val profile = http.get(“http:/.”)                           
    return profile
}

                                                
launch(UI) {
    prograssBar.isVisible = true
    val profile = async { loadProfile() }.await()
    nameText.text = profile.name
    prograssBar.isVisible = false
                                                
}     

async/await是Future/Promise模型的非阻塞版,所以可以像Promise一样方便地实现各种顺序的逻辑,且不必担心阻塞线程

串行执行

launch(UI) {                             
    prograssBar.isVisible = true

    val token = async { getToken() }
    val profile = async { loadProfile(token.await()) }.await()
    nameText.text = profile.name
    
    prograssBar.isVisible = false
                                                
}

并行执行

launch(UI) {                                            
    prograssBar.isVisible = true

    val profile = async { loadProfile() }
    val articles = async { loadArticles() }
    show(profile.await(), articles.await())
    prograssBar.isVisible = false
                                              
} 

 

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

fundroid

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值