美文网首页
初识协程

初识协程

作者: ivotai | 来源:发表于2024-02-16 10:00 被阅读0次
fun fetchAndShowUser() {
    GlobalScope.launch(Dispatchers.Main) {
        val user = fetchUser() // fetch on IO thread
        showUser(user) // back on UI thread
    }
}

suspend fun fetchUser(): User {
    return withContext(Dispatchers.IO) {
        // make network call on IO thread
        // return user
    }
}

fun showUser(user: User) {
    // show user
}
GlobalScope

GlobalScope 只是为了举例,实际中会用轻量级的 lifecycleScope 替代,launch 代表开启协程。

supsend

挂起函数只允许从协程或另一个挂起函数调用。
最终是由协程开始调用。

withContext

withContext是一个挂起函数,所以只能由挂起函数或者协程调用,它负责切换携程上下文,即切换线程。

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        lifecycleScope.launch {
            val user = fetchUser()
            // show user
        }

    }
lifecycleScope

lifecycleScope 是个作用域。
一旦 Activity 被销毁,如果任务正在运行,它就会被取消,因为我们使用了绑定到 Activity 生命周期的作用域。

val deferredJob = GlobalScope.async(Dispatchers.Default) {
    // do something and return result, for example 10 as a result
    return@async 10
}
val result = deferredJob.await() // result = 10
async

当我们需要返回结果时,需要使用 async。
可以使用Deferred作业对象来获取作业的状态或取消它。

相关文章

网友评论

      本文标题:初识协程

      本文链接:https://www.haomeiwen.com/subject/ccbyadtx.html