iT邦幫忙

第 12 屆 iThome 鐵人賽

DAY 26
0

coroutines=cooperation+routines,簡單說是處理非同步需求的機制,這裡routine 指被呼叫的 function、method , 協同其他更多的 function、method 共同作業稱為 coroutines。

其中suspend coroutines 最精神象徵物
suspend 初始化任務,暫時不在調用的線程中,當前線程可以繼續執行別的任務,一旦被任務已經執行完畢,會通過resume將其重新插入到當前線程中。

使用需import jetbrains libary

dependencies {
implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-core:1.3.9'
implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-android:1.3.9'
}

ViewModelScope ,是一種 CoroutineScope,可以透過它 viewModelScope.launch {} 直接呼叫 Kotlin suspend function。

dependencies {
implementation "androidx.lifecycle:lifecycle-viewmodel-ktx:2.2.0"
implementation "androidx.work:work-runtime-ktx:2.4.0"
}

launch

lifecycleScope.launch {
   longTimerProcess()
}
 private suspend fun longTimerProcess(){
    val one = async { doSomethingUsefulOne() }
    val two = async { doSomethingUsefulTwo() }
    println("The answer is ${one + two}")
 }
 
 suspend fun doSomethingUsefulOne(): Int {
  delay(1000L) // pretend we are doing something useful here
  return 13
 }

 suspend fun doSomethingUsefulTwo(): Int {
  delay(1000L) // pretend we are doing something useful here, too
  return 29
  }
 

async

private suspend fun longTimerProcess(){
   val one = async { doSomethingUsefulOne() }
   val two = async { doSomethingUsefulTwo() }
   println("The answer is ${one.await() + two.await()}")
}

async 與 launch 差別,async並發的速度會比較快

runBlocking
確保依造順序而不是併發,常用在UITest

fun main() = runBlocking<Unit> {
 val time = measureTimeMillis {
     val one = async { doSomethingUsefulOne() }
     val two = async { doSomethingUsefulTwo() }
     println("The answer is ${one.await() + two.await()}")
 }
 println("Completed in $time ms")
}

reference:https://www.notion.so/Coroutines-and-multi-threading-9-16-Jast-Lai-d5a7637c35354510a36309a03b9d24d6
reference:https://developer.android.com/kotlin/coroutines
reference:https://kotlinlang.org/docs/reference/coroutines/composing-suspending-functions.html
reference: https://medium.com/jastzeonic/kotlin-coroutine-%E9%82%A3%E4%B8%80%E5%85%A9%E4%BB%B6%E4%BA%8B%E6%83%85-685e02761ae0


上一篇
<Day25>Navigation component(三)
下一篇
<Day 27>Database -Room
系列文
Android App 初學者從零開始用Kotlin寫APP30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言