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
                                              
} 
发布了11 篇原创文章 · 获赞 1 · 访问量 271

猜你喜欢

转载自blog.csdn.net/vitaviva/article/details/104095182