async與launch一樣都是開啟一個協程,但是async會返回一個Deferred對象,該Deferred也是一個job async函數類似於 launch函數.它啟動了一個單獨的協程,這是一個輕量級的線程並與其它所有的協程一起併發的工作.不同之處在於 launch 返回一個 Job 並且不附帶 ...
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