协程的async使用
async与launch一样都是开启一个协程,但是async会返回一个Deferred对象,该Deferred也是一个job
async函数类似于 launch函数.它启动了一个单独的协程,这是一个轻量级的线程并与其它所有的协程一起并发的工作.不同之处在于 launch 返回一个 Job 并且不附带任何结果值,而 async 返回一个 Deferred —— 一个轻量级的非阻塞 future,这代表了一个将会在稍后提供结果的 promise.你可以使用 .await() 在一个延期的值上得到它的最终结果, 但是 Deferred 也是一个 Job
看一下async的使用:
GlobalScope.launch { var deffer1 = async(Dispatchers.IO) { async1() }.await() var deffer2 = async(Dispatchers.IO) { async2() }.await() val result = deffer1 + deffer2 println("the sum is: $result") } private suspend fun async1(): Int { delay(1500) println("async1") return 1 } private suspend fun async2(): Int { delay(300) println("async2") return 2 }
最终输出:
I/System.out: async1 I/System.out: async2 I/System.out: the sum is: 3
async1先执行,说明其是顺序进行的,因为await本身就是一个挂起行数,这时候它的用法与withContext没有什么差别。
再看一个例子:
GlobalScope.launch { var deffer1 = async(Dispatchers.IO) { async1() } var deffer2 = async(Dispatchers.IO) { async2() } Log.d("GlobalScope","before sum") var r1 = deffer1.await() var r2 = deffer2.await() val result = r1 + r2 Log.d("GlobalScope","the sum is -> $result") } private suspend fun async1(): Int { delay(1500) Log.d("GlobalScope","async1") return 1 } private suspend fun async2(): Int { delay(300) Log.d("GlobalScope","async2") return 2 }
打印log:
D/GlobalScope: before sum D/GlobalScope: async2 D/GlobalScope: async1 D/GlobalScope: the sum is -> 3
可以看到async2先执行,因为挂起函数在后面,await是挂起函数。
简化写法:
GlobalScope.launch { var deffer1 = async(Dispatchers.IO) { async1() } var deffer2 = async(Dispatchers.IO) { async2() } Log.d("GlobalScope","before sum") val result = deffer1.await() + deffer2.await() Log.d("GlobalScope","the sum is -> $result") }
打印log:
D/GlobalScope: before sum D/GlobalScope: async2 D/GlobalScope: async1 D/GlobalScope: the sum is -> 3