launch和async最大的不同点在于launch被用于不关注执行返回结果的计算,概念上和线程池中的Runnable很像。但是launch会返回一个Job对象,这个Job对象表示当前的coroutine,可以用于控制当前计算的生命周期。调用的Job.join()方法可能会阻塞直到launch中的计算完成。 实际上之前提到的Deferred是继承Job的泛型类,区别在于Deferred...
1、对比 launch 和 async 创建的协程的异常捕捉示例 代码示例 : 使用launch 构造的协程 , 可以使用 CoroutineExceptionHandler 捕获异常 ; 使用async 构造的协程 , 无法使用 CoroutineExceptionHandler 捕获异常 , 异常直接抛出 , 导致程序崩溃 ; package kim.hsl.coroutine import android.os.Bundle import android.uti...
GlobalScope.launch(Dispatchers.IO) { fetchUserAndSaveInDatabase() // do on IO thread } 1. 2. 3. 由于fetchUserAndSaveInDatabase不返回任何内容,我们可以使用launch。 但是当我们需要返回结果时,我们需要使用async。 我们有两个函数返回User,如下所示: fun fetchFirstUser(): User { // make network ...
launch函数是一种协程构建器,它用于创建并启动一个新的协程。launch函数返回一个Job对象,我们可以使用这个对象来管理协程的生命周期。 val job=GlobalScope.launch{doSomething()}job.cancel()// 取消协程 1.6async async函数也是一种协程构建器,它用于创建并启动一个新的协程。与launch函数不同,async函数返回一个Defe...
* 本利用于演示协程基础,包括 CoroutineScope, 为 CoroutineScope 扩展方法, runBlocking, launch, async, await, suspend, withContext, 设置/获取 CoroutineScope 的名称 * * 进程是资源分配的最小单位,不同进程之间资源都是独立的 * 线程是 CPU 调度的基本单位,本身并不拥有系统资源,所有线程会共享进程的资源 ...
所有协程构造器(如 launch 和 async)都接受一个可选参数,即 CoroutineContext ,该参数可用于显式指定要创建的协程和其它上下文元素所要使用的调度器 请尝试以下示例: import kotlinx.coroutines.* fun main() = runBlocking<Unit> { //sampleStart launch { // context of the parent, main runBlocking corouti...
CoroutineBuilder:负责创建和启动新协程的函数。例如,launch{}、async{}、runBlocking{}。 挂起函数(Suspend Function):可以挂起和恢复代码执行而不阻塞线程的函数。它只能在挂起函数或协程块中调用。 CoroutineContext:为协程提供上下文信息(CoroutineDispatcher、Job、CoroutineExceptionHandler)。它还告诉协程需要在哪个线程上...
GlobalScope 是 CoroutineScope 的实现类。我们以前使用过的 launch、async 函数都是 CoroutineScope 的扩展函数。 GlobalScope 没有绑定任何 Job 对象,它用于构建最顶层的协程。这些协程的生命周期会跟随着 Application。 在GlobalScope 中创建的 Coroutines,是有可能会导致应用崩溃的。
在coroutineScope中的启动块中,异常不会被自动捕获。coroutineScope是一个协程作用域构建器,用于创建一个新的协程作用域,在该作用域内启动的所有协程都会被取消,以及它们的异常会被...
3.1.1 launch() Launches a new coroutine without blocking the current thread and returns a reference to the coroutine as aJob. CoroutineScope Defines a scope for new coroutines. Everycoroutine builder(likelaunch,async, etc.) is an extension onCoroutineScopeand inherits itscoroutineContextto automati...