Kotlin中协程的基本使用

本文介绍了Kotlin协程的四种创建方式:launch()、async()、withContext()和runBlocking(),详细解析了它们的使用场景和特点。此外,还探讨了Job和Deferred的概念,包括Job的状态管理和Deferred的返回值获取。
摘要由CSDN通过智能技术生成

1.协程的创建方式

1.使用 launch()
  • 实例如下:
GlobalScope.launch {
        delay(3000)
    }
  • launch()函数的源代码如下:
public fun CoroutineScope.launch(
    context: CoroutineContext = EmptyCoroutineContext,
    start: CoroutineStart = CoroutineStart.DEFAULT,
    block: suspend CoroutineScope.() -> Unit
): Job {
    val newContext = newCoroutineContext(context)
    val coroutine = if (start.isLazy)
        LazyStandaloneCoroutine(newContext, block) else
        StandaloneCoroutine(newContext, active = true)
    coroutine.start(start, coroutine, block)
    return coroutine
}

context :

接收一个可选的 CoroutineContext 参数,是一些元素的集合,主要包括 Job 和 CoroutineDispatcher 元素。可以代表一个协程的场景。默认值EmptyCoroutineContext,表示运行在父协程的上下文中。 其他值如下

  1. Dispatchers.Unconfined :协程调度器会在程序运行到第一个挂起点时,在调

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值