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
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/526945.html
標籤:其他
