Thuta Learning
Kotlin
AdvancedProgrammingအခြေခံ

Advanced Kotlin Coroutines

Kotlinသင်ခန်းစာ 2445 မိနစ်

ဒီခန်းပြီးရင် ဘာတတ်သွားမလဲ

  • suspend ဆိုတာ ဘာလဲ၊ delay() က thread ကို မပိတ်ဘဲ ဘာကြောင့် စောင့်နိုင်လဲ ဆိုတာ ရှင်းပြနိုင်ဖို့
  • အလုပ်တစ်ခုအတွက် runBlocking, launch, async, coroutineScope နဲ့ withContext ထဲက သင့်တော်တာကို ရွေးနိုင်ဖို့
  • အလုပ်ကို cooperative ဖြစ်အောင် cancel လုပ်နိုင်ပြီး CancellationException ကို မျိုမထားဘဲ ပြန် throw နိုင်ဖို့
  • coroutineScope နဲ့ supervisorScope မှာ child တစ်ခု fail ရင် sibling တွေ ဘာဖြစ်လဲ ကြိုတင် ခန့်မှန်းနိုင်ဖို့
  • CPU သုံးတဲ့ အလုပ်နဲ့ blocking အလုပ်အတွက် Dispatchers.Default ဒါမှမဟုတ် Dispatchers.IO ကို ရွေးနိုင်ဖို့

ရိုးရိုးလေး ရှင်းပြမယ်

Coroutine ကို ရိုးရိုးလေး ပြောရရင်

Coroutine ဆိုတာ စောင့်နေတဲ့အချိန်မှာ thread တစ်ခုကို ချုပ်ထားစရာမလိုဘဲ ခဏရပ်ပြီး နောက်မှ ဆက်လုပ်နိုင်တဲ့ အလုပ်တစ်ခုပါ။ လူစည်တဲ့ စားသောက်ဆိုင်က waiter တစ်ယောက်ကို စဉ်းစားကြည့်ပါ။ Order ယူပြီးရင် အစားအစာ ရတဲ့အထိ မီးဖိုချောင် ပြတင်းပေါက်မှာ ရပ်မစောင့်ပါဘူး၊ တခြားစားပွဲတွေကို ဝန်ဆောင်မှုပေးနေပြီး ခေါင်းလောင်းမြည်မှ ပြန်လာပါတယ်။ Suspend function ဆိုတာ အဲဒီ waiter ကို ထွက်သွားခွင့် ပေးထားတဲ့ အလုပ်ရဲ့ အပိုင်းပါပဲ။

Kotlin က suspend ဆိုတဲ့ language keyword တစ်ခုနဲ့ launch, async, delay နဲ့ dispatcher တွေ ပေးတဲ့ kotlinx.coroutines library တစ်ခုကို သုံးပြီး ဒါကို ထောက်ပံ့ပါတယ်။ Compiler က suspend function တစ်ခုချင်းစီကို ပြန်စလို့ရတဲ့ state machine အဖြစ် ပြောင်းရေးပေးတဲ့အတွက် စောင့်ရတာဟာ thread တစ်ခု ပိတ်မိတာ မဟုတ်ဘဲ object သေးသေးလေး တစ်ခုပဲ ကုန်ပါတယ်။ ဒါကြောင့် thread ရာနဲ့ချီပဲ ခံနိုင်တဲ့ နေရာမှာ coroutine ထောင်ပေါင်းများစွာ run နိုင်တာပါ။

Problem → Why → Solution

ပြဿနာ: thread ကို ချုပ်ထားတဲ့ စောင့်ဆိုင်းမှု

Profile screen တစ်ခုက user ရဲ့ နာမည် (120 ms ကွာ) နဲ့ order အရေအတွက် (150 ms ကွာ) ကို လိုပါတယ်။ ရိုးရိုး blocking call တွေနဲ့ဆိုရင် စောင့်တိုင်း thread တစ်ခုလုံး ပိတ်မိနေပါတယ်။ Call နှစ်ခုက တစ်ခုပြီးမှ တစ်ခု run တဲ့အတွက် screen ပြီးဖို့ ၂၇၀ ms လောက် ကြာပြီး အဲဒီအချိန်တစ်လျှောက် thread က အသုံးဝင်တာ ဘာမှ မလုပ်ပါဘူး။ Request တစ်ထောင် တစ်ပြိုင်နက် ကိုင်တဲ့ server မှာ thread တစ်ထောင် ပိတ်မိနေမှာဖြစ်ပြီး Android မှာဆိုရင် main thread ရပ်သွားလို့ app က တုံ့ဆိုင်းပါလိမ့်မယ်။

အလွယ်လမ်းတွေက ပြဿနာအသစ် ထပ်ဖြစ်စေပါတယ်။ Thread အစစ် စတင်တာ ဒါမှမဟုတ် GlobalScope.launch သုံးတာက call တွေကို ထပ်နေအောင် လုပ်ပေးပေမဲ့ အလုပ်ကို ပိုင်ဆိုင်တဲ့သူ မရှိတော့ပါဘူး။ ဘယ်သူမှ စောင့်မယ့်သူ မရှိ၊ user က screen ကနေ ထွက်သွားရင် cancel လုပ်ပေးမယ့်သူ မရှိ၊ အထဲက failure ကလည်း အဲဒီအလုပ်ကို စတင်ခဲ့တဲ့ code ဆီ ဘယ်တော့မှ မရောက်ပါဘူး။

BlockingProfile.kt
// Every call parks a whole thread while it waits.
fun loadName(id: Int): String {
    Thread.sleep(120)            // stands in for a network call
    return "user-$id"
}

fun loadOrderCount(id: Int): Int {
    Thread.sleep(150)
    return id * 3
}

fun main() {
    val name = loadName(1)            // 120 ms, thread blocked
    val orders = loadOrderCount(1)    // 150 ms more, thread blocked again
    println("$name has $orders orders")  // printed about 270 ms later
}

စောင့်တာနဲ့ အလုပ်လုပ်တာ မတူပါဘူး

Network ကို စောင့်နေတဲ့အချိန်မှာ code က ဘာမှ တွက်ချက်နေတာ မဟုတ်လို့ thread တစ်ခုကို သိမ်းထားစရာ မလိုပါဘူး။ Coroutine တွေက အဲဒီအတွေးနှစ်ခုကို ခွဲပေးပါတယ်: suspend ဖြစ်နေတဲ့ coroutine က သူ့ thread ကို တခြားအလုပ်အတွက် လွှတ်ပေးပြီး scope ကတော့ launch လုပ်ထားတဲ့ coroutine တိုင်းကို စောင့်မယ်၊ cancel လုပ်မယ်၊ failure ကို လက်ခံမယ့် parent တစ်ခုနဲ့ ချိတ်ထားပေးပါတယ်။ ဒီလိုနဲ့ ဘယ်အလုပ်ကို ဘယ်သူ တာဝန်ယူလဲ ဆိုတာ မပျောက်ဘဲ concurrency ရပါတယ်။

Core concept: suspend, builder နဲ့ scope

suspend modifier က function တစ်ခုကို အလယ်မှာ ခဏရပ်နိုင်တယ်လို့ ကြေညာပါတယ်။ Suspend function ကို တခြား suspend function ထဲကနဲ့ coroutine builder ထဲကပဲ ခေါ်လို့ရပါတယ်၊ ရိုးရိုး function ကနေ ခေါ်ရင် compile error ပါ။ delay(120) က 120 ms စောင့်ပေမဲ့ Thread.sleep နဲ့ မတူဘဲ coroutine ကို suspend လုပ်ပြီး thread ကို လွှတ်ပေးပါတယ်၊ အချိန်စေ့ရင် dispatcher က coroutine ကို ပြန်စပေးပါတယ်။

Coroutine builder တွေကတော့ coroutine ကို စတင်ပေးတဲ့ function တွေပါ။ ဘယ်တစ်ခုက ဘာအတွက်လဲဆိုတာ အောက်က table မှာ ကြည့်ပါ။ အရေးအကြီးဆုံးကွာခြားချက်က launch က Job ကို ပြန်ပေးပြီး ရလဒ်တန်ဖိုး မရှိတာ၊ async က Deferred<T> ပြန်ပေးပြီး await() နဲ့ ရလဒ်ကို ယူရတာပါ။

Builderပြန်ပေးတာသုံးရမယ့်နေရာ
runBlockinglambda ရဲ့ ရလဒ်main() နဲ့ test တွေ၊ ခေါ်တဲ့ thread ကို ပိတ်ထားတယ်
launchJobscope တစ်ခုထဲမှာ ရလဒ်မလိုတဲ့ အလုပ်
asyncDeferred<T>တစ်ပြိုင်နက် လုပ်ပြီး await လုပ်မယ့် တန်ဖိုး
coroutineScopelambda ရဲ့ ရလဒ်suspend function ထဲမှာ child coroutine တွေကို အုပ်စုဖွဲ့ဖို့
withContextlambda ရဲ့ ရလဒ်block တစ်ခုအတွက် dispatcher ပြောင်းဖို့

Structured concurrency ဆိုတာ coroutine တိုင်းမှာ parent Job ရှိပြီး အဲဒီ parent က child အားလုံး ပြီးတဲ့အထိ စောင့်ရတယ်ဆိုတဲ့ စည်းမျဉ်းပါ။ Parent ကို cancel လုပ်ရင် child တွေပါ cancel ဖြစ်ပြီး child တစ်ခု fail ရင် parent ကိုပါ cancel လုပ်ကာ sibling တွေကိုလည်း ရပ်စေပါတယ်။ အဲဒါကြောင့် coroutineScope { ... } ပြီးသွားပြီဆိုရင် အထဲက အလုပ်အားလုံး ပြီးပြီ (ဒါမှမဟုတ် ရပ်သွားပြီ) လို့ သေချာနိုင်ပါတယ်၊ အလုပ်တစ်ခု နောက်ကွယ်မှာ ကျန်နေခဲ့တာ မရှိပါဘူး။ GlobalScope ကတော့ ဒီစည်းမျဉ်းကို ကျော်သွားတဲ့အတွက် လက်တွေ့ app code မှာ ရှောင်သင့်ပါတယ်။

Cancellation က cooperative ဖြစ်ပါတယ်။ cancel() က coroutine ကို အတင်းမရပ်ပါဘူး၊ job ကို cancelled လို့ အမှတ်အသားထားရုံပါပဲ၊ coroutine က နောက်ဆုံး suspension point မှာ ဒါကို သတိပြုမိပြီး CancellationException ကို throw လုပ်ပါတယ်။ အဲဒီ exception က error မဟုတ်ဘဲ 'ရပ်လိုက်ပါပြီ' ဆိုတဲ့ ပုံမှန် signal ဖြစ်လို့ catch လုပ်ရင် ပြန် throw ရပါမယ်။

Scope ကို job တွေရဲ့ သစ်ပင်လို မြင်ပါ
  1. Scope က root Job ကို ပိုင်တယ်
  2. launch/async က child Job ထပ်ထည့်
  3. Parent က child အားလုံးကို စောင့်
  4. Cancel က အောက်ကို၊ failure က အပေါ်ကို

Coroutine ကို စောင့်ပေးမယ့် scope မရှိရင် (GlobalScope လို) ဘယ်သူမှ cancel လုပ်မှာ၊ စောင့်မှာ၊ failure ကို ကြားမှာ မဟုတ်ပါဘူး။

အထွေထွေ ပုံစံ

kotlin
suspend fun task(arg: Type): Result {
    delay(millis)                      // any suspending call
    return value
}

suspend fun combined(): Combined = coroutineScope {
    val first = async { task(a) }      // starts right away
    val second = async { task(b) }     // runs alongside first
    Combined(first.await(), second.await())
}

Suspend function ထဲမှာ suspending call တွေကို ခေါ်ပါ။ Concurrent ဖြစ်စေချင်ရင် coroutineScope ထဲမှာ async တစ်ခုချင်းစီ စတင်ပြီး နောက်မှ await လုပ်ပါ၊ ဒါမှ child တွေက တစ်ခုချင်း မစောင့်ဘဲ ထပ်နေပါတယ်။

Worked example: profile တွေကို တစ်ပြိုင်နက် load လုပ်ခြင်း

loadProfile က coroutineScope ထဲမှာ async child နှစ်ခု စတင်တဲ့အတွက် နာမည်နဲ့ order အရေအတွက်ကို တစ်ပြိုင်နက် ယူပါတယ်။ ပြီးတော့ main က awaitAll နဲ့ profile သုံးခုကို တစ်ပြိုင်နက် တောင်းပြီး ရလဒ်အားလုံးကို နေရာတစ်ခုတည်းကနေ print ထုတ်တဲ့အတွက် အလုပ်တွေ ထပ်နေပေမဲ့ output အစီအစဉ်က အမြဲတူပါတယ်။

ဒီမှာ runBlocking ဘာကြောင့် သုံးလဲ

main က ရိုးရိုး function ဖြစ်ပြီး ရိုးရိုး function က suspend function ကို မခေါ်နိုင်ပါဘူး။ runBlocking က အဲဒီကြား တံတားပါ: သူ့ coroutine ပြီးတဲ့အထိ ခေါ်တဲ့ thread ကို ပိတ်ထားပါတယ်။ main() နဲ့ test တွေမှာ မှန်ပေမဲ့ တခြား coroutine ထဲမှာတော့ မသုံးသင့်ပါဘူး။ suspend fun main() လို့ တိုက်ရိုက် ကြေညာတာလည်း Kotlin က လက်ခံပါတယ်။

Profiles.kt
import kotlinx.coroutines.*

data class Profile(val name: String, val orders: Int)

suspend fun loadName(id: Int): String {
    delay(120)
    return "user-$id"
}

suspend fun loadOrderCount(id: Int): Int {
    delay(150)
    return id * 3
}

suspend fun loadProfile(id: Int): Profile = coroutineScope {
    val name = async { loadName(id) }
    val orders = async { loadOrderCount(id) }
    Profile(name.await(), orders.await())
}

fun main() = runBlocking {
    val profiles = (1..3).map { id -> async { loadProfile(id) } }.awaitAll()
    profiles.forEach { println(it) }
    println("total orders: ${profiles.sumOf { it.orders }}")
}

Code ကို တစ်ပိုင်းချင်း ရှင်းပြမယ်

  1. suspend and delaydelay(120)

    delay က coroutine ကို suspend လုပ်ပြီး thread ကို လွှတ်ပေးပါတယ်။ Network call အစစ်လည်း ဒီပုံစံပါပဲ: စောင့်နေတုန်း thread က တခြား coroutine တွေကို ကူညီနိုင်ပါတယ်။

  2. Concurrent childrenval name = async { loadName(id) }

    async က child coroutine ကို ချက်ချင်း စတင်ပြီး Deferred ပြန်ပေးပါတယ်။ နောက် line က async ကိုပါ ဆက်စတင်တဲ့အတွက် loadName နဲ့ loadOrderCount တို့ ထပ်နေပါတယ်။

  3. Await the resultsProfile(name.await(), orders.await())

    await() က ရလဒ် အဆင်သင့်ဖြစ်တဲ့အထိ suspend လုပ်ပြီး တန်ဖိုးကို ပေးပါတယ်။ ၁၅၀ ms ယူတဲ့ child ကြောင့် loadProfile တစ်ခုလုံး ၂၇၀ ms မဟုတ်ဘဲ ၁၅၀ ms ဝန်းကျင်ပဲ ကြာပါတယ်။

  4. Bridge from blocking codefun main() = runBlocking {

    runBlocking က main ကို coroutine ကမ္ဘာထဲ ဝင်ခွင့်ပေးပါတယ်။ ဒီ block ထဲက code တွေက suspend function တွေကို ခေါ်လို့ရပြီး block ပြီးမှ main ပြီးပါတယ်။

  5. Fan out, then gatherval profiles = (1..3).map { id -> async { loadProfile(id) } }.awaitAll()

    map က async သုံးခုကို အရင်စတင်ပြီး awaitAll က အားလုံးကို စောင့်ကာ ရလဒ်တွေကို child တွေ စတင်ခဲ့တဲ့ အစီအစဉ်အတိုင်း list အဖြစ် ပြန်ပေးပါတယ်။ ဒါကြောင့် user-1, user-2, user-3 အစီအစဉ်က မပြောင်းပါဘူး။

You should see
Profile(name=user-1, orders=3)
Profile(name=user-2, orders=6)
Profile(name=user-3, orders=9)
total orders: 18
loadProfile run တဲ့အခါ ဘာဖြစ်လဲ
  1. loadProfile က async child နှစ်ခု စတင်
  2. နှစ်ခုလုံး delay မှာ suspend ဖြစ်၊ thread လွတ်
  3. Timer စေ့တဲ့အခါ child တွေ ပြန်စပြီး တန်ဖိုးပေး
  4. နှစ်ခုလုံး ပြီးမှ coroutineScope ပြန်ထွက်

Cancellation က cooperative ဖြစ်တယ်

Job တစ်ခုကို cancel လုပ်တာနဲ့ coroutine က ချက်ချင်း မရပ်ပါဘူး။ delay, await, yield လို kotlinx.coroutines ထဲက suspending function တိုင်းက cancellation ရှိမရှိ စစ်ပြီး CancellationException ကို throw လုပ်ပါတယ်။ ဘယ်တော့မှ suspend မလုပ်တဲ့ loop ကတော့ ဘာမှ သတိမပြုမိတဲ့အတွက် CPU သုံးတဲ့ loop ရှည်တွေက ensureActive() ကို (ဒါမှမဟုတ် isActive ကို) ကိုယ်တိုင် စစ်ရပါမယ်။

CooperativeCancel.kt
import kotlinx.coroutines.*

fun main() = runBlocking {
    val polite = mutableListOf<Int>()
    val stubborn = mutableListOf<Int>()

    val a = launch {
        for (i in 1..5) {
            ensureActive()
            polite += i
            if (i == 3) coroutineContext.job.cancel()
        }
    }
    val b = launch {
        for (i in 1..5) {
            stubborn += i
            if (i == 3) coroutineContext.job.cancel()
        }
    }
    joinAll(a, b)
    println("with ensureActive: $polite, cancelled=${a.isCancelled}")
    println("without any check: $stubborn, cancelled=${b.isCancelled}")
}

Coroutine နှစ်ခုလုံးက item 3 ရောက်ရင် ကိုယ့်ကိုယ်ကို cancel လုပ်ပါတယ်။ ပထမတစ်ခုက pass တိုင်း ensureActive() ကို ခေါ်လို့ [1, 2, 3] မှာ ရပ်သွားပြီး ဒုတိယတစ်ခုက ဘာမှ မစစ်တဲ့အတွက် job က cancelled ဖြစ်နေပေမဲ့ item ငါးခုလုံး ပြီးအောင် ဆက်လုပ်ပါတယ်။ Print ထုတ်တဲ့ output က with ensureActive: [1, 2, 3], cancelled=true နဲ့ without any check: [1, 2, 3, 4, 5], cancelled=true ဖြစ်ပါတယ်။

Cleanup နဲ့ timeout

Cancel ခံရတဲ့ coroutine က CancellationException နဲ့ ပြန်လည် ပြေလျော့ဆင်းပါတယ်၊ ဒါကြောင့် cleanup လုပ်စရာရှိရင် finally ထဲမှာ ဒါမှမဟုတ် ပြန် throw လုပ်တဲ့ catch ထဲမှာ ထားပါ။ withTimeout က အချိန်ကုန်ရင် သူ့ block ကို cancel လုပ်ပြီး TimeoutCancellationException ကို throw လုပ်ပါတယ်၊ withTimeoutOrNull ကတော့ exception အစား null ပြန်ပေးပါတယ်။

CleanupAndTimeout.kt
import kotlinx.coroutines.*

fun main() = runBlocking {
    val worker = launch {
        try {
            println("worker: waiting")
            delay(10_000)
        } catch (e: CancellationException) {
            println("worker: cleaning up after ${e::class.simpleName}")
            throw e
        } finally {
            println("worker: finally runs")
        }
    }
    delay(50)
    worker.cancelAndJoin()
    println("worker cancelled: ${worker.isCancelled}")

    val fast = withTimeoutOrNull(100) { delay(20); "fast result" }
    val slow = withTimeoutOrNull(100) { delay(200); "slow result" }
    println("fast=$fast slow=$slow")

    try {
        withTimeout(60) { delay(200) }
    } catch (e: TimeoutCancellationException) {
        println("timeout: ${e.message}")
    }
}

Output က worker: waiting, worker: cleaning up after JobCancellationException, worker: finally runs, worker cancelled: true, fast=fast result slow=null နဲ့ timeout: Timed out waiting for 60 ms ဆိုပြီး ဒီအစီအစဉ်အတိုင်း ထွက်ပါတယ်။ cancelAndJoin() က worker ရဲ့ cleanup ပြီးတဲ့အထိ စောင့်ပေးလို့ cleanup message တွေက နောက်ဆုံး println မတိုင်ခင် ထွက်တာပါ။

Child တစ်ခု fail ရင် ဘာဖြစ်လဲ

coroutineScope ထဲမှာ ပထမဆုံး failure က တခြား child တွေကို cancel လုပ်ပြီး coroutineScope ကိုယ်တိုင်က exception ကို ပြန် throw လုပ်ပါတယ်၊ ဒါကြောင့် scope ကို try/catch နဲ့ ပတ်ထားရင် ဖမ်းမိပါတယ်။ supervisorScope ကတော့ စည်းမျဉ်းကို ပြောင်းပါတယ်: child တွေက တစ်ခုနဲ့တစ်ခု သီးခြား fail ပြီး await လုပ်တဲ့နေရာမှာ failure တစ်ခုချင်းစီကို ကိုင်တွယ်ရပါတယ်။

ChildFailure.kt
import kotlinx.coroutines.*

suspend fun download(id: Int): String {
    delay(40L * id)
    if (id == 2) throw IllegalStateException("file $id is corrupt")
    return "file-$id"
}

fun main() = runBlocking {
    val all = try {
        coroutineScope {
            (1..3).map { id -> async { download(id) } }.awaitAll()
        }
    } catch (e: IllegalStateException) {
        listOf("coroutineScope failed: ${e.message}")
    }
    println(all)

    val each = supervisorScope {
        (1..3).map { id -> async { download(id) } }.map { job ->
            try {
                job.await()
            } catch (e: IllegalStateException) {
                "failed (${e.message})"
            }
        }
    }
    println(each)
}

ပထမ output က [coroutineScope failed: file 2 is corrupt] ဖြစ်ပါတယ်: file-3 ကို မပြီးခင် cancel လုပ်လိုက်လို့ ရလဒ်မရှိတော့ပါဘူး။ ဒုတိယ output က [file-1, failed (file 2 is corrupt), file-3] ဖြစ်ပြီး supervisorScope မှာ ကျန်တဲ့ child နှစ်ခု ပုံမှန်ပြီးသွားပါတယ်။

Dispatcher: code ကို ဘယ်မှာ run မလဲ

Dispatcher က coroutine ကို ဘယ် thread (ဒါမှမဟုတ် thread pool) ပေါ်မှာ run မလဲ ဆုံးဖြတ်ပါတယ်။ runBlocking ထဲက coroutine တွေက ခေါ်လိုက်တဲ့ thread ပေါ်မှာ run ပြီး withContext(Dispatchers.Default) လို့ ရေးရင် block တစ်ခုကို တခြား pool ကို ပို့ပြီး ရလဒ်ကို ပြန်ပေးပါတယ်။ အသုံးများတဲ့ dispatcher တွေကို အောက်က table မှာ ကြည့်ပါ။

Dispatcherဘာအတွက်လဲမှတ်ချက်
Dispatchers.DefaultCPU သုံးတဲ့ အလုပ်: sort, parse, image processingCPU core အရေအတွက်နဲ့ ညီတဲ့ shared pool
Dispatchers.IOBlocking call: file, JDBC, blocking HTTP clientDefault နဲ့ thread မျှသုံးပြီး ပိုကြီးတဲ့ pool အထိ ကြီးနိုင်
Dispatchers.MainUI ကို update လုပ်ခြင်းAndroid, Swing, JavaFX လို UI artifact ပါမှ ရှိတယ်၊ သာမန် JVM မှာ IllegalStateException
Dispatchers.kt
import kotlinx.coroutines.*

fun main() = runBlocking {
    val log = mutableListOf<String>()
    println("main thread: ${Thread.currentThread().name}")

    val onDefault = withContext(Dispatchers.Default) {
        Thread.currentThread().name.startsWith("DefaultDispatcher-worker")
    }
    val onIo = withContext(Dispatchers.IO) {
        Thread.currentThread().name.startsWith("DefaultDispatcher-worker")
    }
    println("Default uses the shared pool: $onDefault, IO uses the shared pool: $onIo")
    println("back on: ${Thread.currentThread().name}")

    val blocking = launch { log += "A start"; Thread.sleep(60); log += "A end" }
    val other = launch { log += "B start"; log += "B end" }
    joinAll(blocking, other)
    println("Thread.sleep: $log")
    log.clear()

    val suspending = launch { log += "A start"; delay(60); log += "A end" }
    val other2 = launch { log += "B start"; log += "B end" }
    joinAll(suspending, other2)
    println("delay:        $log")
}

ပထမ println က main thread: main ကို ပြပြီး withContext ပြီးတဲ့အခါ coroutine က main thread ပေါ် ပြန်ရောက်ပါတယ်။ နောက်ဆုံး output နှစ်ကြောင်းက အရေးအကြီးဆုံးပါ: Thread.sleep နဲ့ဆိုရင် A က thread တစ်ခုတည်းကို ချုပ်ထားလို့ B က A ပြီးမှ စနိုင်ပြီး [A start, A end, B start, B end] ဖြစ်ပါတယ်။ delay နဲ့ဆိုရင် A က suspend ဖြစ်ပြီး thread ကို လွှတ်ပေးလို့ B က ကြားထဲမှာ ပြီးသွားပြီး [A start, B start, B end, A end] ဖြစ်ပါတယ်။

Project ထဲကို library ထည့်ခြင်း

suspend keyword က language ထဲမှာ ပါပေမဲ့ launch, async, delay, dispatcher တွေက kotlinx.coroutines library ထဲမှာ ရှိပါတယ်၊ ဒါကြောင့် Gradle project တိုင်းမှာ dependency အနေနဲ့ ထည့်ရပါတယ်။ Version နံပါတ်ကို ကိုယ့်ဘာသာ ရွေးမယ့်အစား official release page မှာ လက်ရှိ version ကို စစ်ပြီး ထည့်ပါ။ Test အတွက် runTest ပေးတဲ့ kotlinx-coroutines-test ကို သီးခြား ထည့်ရပါတယ်။

build.gradle.kts
dependencies {
    // replace <version> with the current kotlinx.coroutines release
    implementation("org.jetbrains.kotlinx:kotlinx-coroutines-core:<version>")
    testImplementation("org.jetbrains.kotlinx:kotlinx-coroutines-test:<version>")
}

လက်တွေ့ project တွေမှာ

လက်တွေ့ project တွေမှာ coroutine ကို ဘယ်မှာ တွေ့ရလဲ

Coroutine တွေက Android နဲ့ Kotlin server project တွေမှာ asynchronous code ရေးဖို့ စံနည်းလမ်း ဖြစ်နေပါပြီ။ အဲဒီ project တွေမှာ အဓိက ပုံစံ ဒီလိုပါ: scope တစ်ခုကို အလုပ်ရဲ့ သက်တမ်းနဲ့ ချိတ်ပြီး အဲဒီထဲမှာ suspend function တွေကို ခေါ်ပါတယ်။

  • Android: viewModelScope.launch နဲ့ lifecycleScope က screen ဒါမှမဟုတ် ViewModel ပျက်သွားတဲ့အခါ အလုပ်တွေကို အလိုအလျောက် cancel လုပ်ပေးလို့ user ထွက်သွားပြီးမှ ပြီးတဲ့ network call က UI ကို မထိတော့ပါဘူး။
  • Ktor နဲ့ Spring WebFlux လို server တွေ: request တစ်ခုချင်းစီကို coroutine တစ်ခုက ကိုင်ပြီး handler တွေက suspend function ဖြစ်နိုင်လို့ database ဒါမှမဟုတ် တခြား service ကို စောင့်နေတုန်း thread တွေက request တွေအများကြီးကို ဆက်ဝန်ဆောင်နိုင်ပါတယ်။
  • Fan-out နဲ့ timeout: service သုံးခုကို async နဲ့ တစ်ပြိုင်နက် ခေါ်ပြီး withTimeoutOrNull နဲ့ နှေးတာကို ဖြတ်ကာ ရလဒ်တစ်စိတ်တစ်ပိုင်းနဲ့ response ပြန်တာမျိုးက အသုံးများပါတယ်။
  • Test: kotlinx-coroutines-test ရဲ့ runTest က delay တွေကို virtual time နဲ့ ကျော်ပေးလို့ စက္ကန့်ရှည်တဲ့ အလုပ်တွေကို မီလီစက္ကန့်နဲ့ test လုပ်နိုင်ပါတယ်။

အမှားများ

Coroutine နဲ့ ဖြစ်လေ့ရှိတဲ့ အမှားများ

Coroutine ထဲမှာ blocking call ခေါ်ခြင်း

Thread.sleep, blocking JDBC ဒါမှမဟုတ် ဖိုင်ဖတ်တာတွေက coroutine ကို suspend မလုပ်ဘဲ thread ကို ချုပ်ထားပါတယ်။ Thread ရှိတဲ့ pool ကုန်သွားရင် တခြား coroutine အားလုံး တန့်သွားပါလိမ့်မယ်။ delay ကို သုံးပါ၊ ဒါမှမဟုတ် blocking code ကို withContext(Dispatchers.IO) ထဲ ထည့်ပါ။

GlobalScope.launch ကို သုံးခြင်း

GlobalScope မှာ parent job မရှိလို့ program ပြီးသွားရင်တောင် လုပ်ဆဲ အလုပ်ကို ဘယ်သူမှ မစောင့်ပါဘူး။ ဒီ code မှာ main က 'main ends' ကို print ထုတ်ပြီး ပြီးသွားတဲ့အတွက် delay(100) နောက်က println("late") က ဘယ်တော့မှ မထွက်ပါဘူး။ Compiler ကပါ 'this is a delicate API and its use requires care' ဆိုပြီး သတိပေးပါတယ်။ coroutineScope ဒါမှမဟုတ် ကိုယ်ပိုင် lifecycle scope ကို သုံးပါ။

CancellationException ကို မျိုချထားခြင်း

catch (e: Exception) ဒါမှမဟုတ် runCatching က CancellationException ကိုပါ ဖမ်းမိပါတယ်။ အဲဒါကို မှတ်တမ်းတင်ပြီး ဆက်သွားရင် cancel လုပ်ထားတဲ့ coroutine က ဆက်လည်ပတ်နေပါတယ်။ အောက်က code မှာ worker ကို cancel လုပ်ပြီးနောက်မှာတောင် 'still running after cancel' ထွက်လာပါတယ်။ ဖမ်းရမယ့် exception ကို ပိုတိတိကျကျ ရွေးပါ ဒါမှမဟုတ် CancellationException ကို ပြန် throw ပါ။

async ကို ချက်ချင်း await လုပ်ခြင်း

async { work() }.await() က လုပ်ငန်းကို အစပြုပြီး ချက်ချင်း စောင့်တဲ့အတွက် concurrency မရတော့ဘဲ work() ကို တိုက်ရိုက်ခေါ်တာနဲ့ အတူတူပါပဲ။ async အားလုံးကို အရင်စတင်ပြီး မှသာ await ပါ။ Dispatcher ပြောင်းချင်ရင်တော့ async မဟုတ်ဘဲ withContext ကို သုံးပါ။

SwallowedCancel.kt
import kotlinx.coroutines.*

fun main() = runBlocking {
    val worker = launch {
        try {
            delay(1000)
        } catch (e: Exception) {
            println("swallowed ${e::class.simpleName}")
        }
        println("still running after cancel")
    }
    delay(30)
    worker.cancelAndJoin()
    println("worker cancelled: ${worker.isCancelled}")
}
GlobalScopeLeak.kt
import kotlinx.coroutines.*

fun main() {
    GlobalScope.launch {
        delay(100)
        println("late")      // never printed: main has already returned
    }
    println("main ends")
}

Best Practices

Best practices

  • Suspend function ကို main-safe ဖြစ်အောင် ရေးပါ: blocking အလုပ်ရှိရင် function ကိုယ်တိုင်က withContext နဲ့ dispatcher ပြောင်းပါ၊ ခေါ်သူကို မမှီခိုပါနဲ့။
  • Concurrent အလုပ်တွေကို coroutineScope ထဲမှာ ထားပြီး function ကနေ ပြန်ထွက်တဲ့အခါ child အားလုံး ပြီးသွားတယ်လို့ အာမခံပါ။
  • Dispatcher ကို class ထဲမှာ hardcode မလုပ်ဘဲ constructor parameter အဖြစ် လက်ခံပါ၊ test တွေက ကိုယ်ပိုင် dispatcher ထည့်လို့ရပါတယ်။
  • supervisorScope ကို child တွေ သီးခြား fail ရမယ်လို့ တမင်ရွေးတဲ့အခါမှ သုံးပြီး failure တစ်ခုချင်းစီကို await လုပ်တဲ့နေရာမှာ ကိုင်တွယ်ပါ။

Mini challenge

Mini challenge: နှေးတဲ့ source ကို ဖြတ်တဲ့ price board

Symbol စာရင်းတစ်ခုရဲ့ စျေးနှုန်းတွေကို တစ်ပြိုင်နက် ယူတဲ့ loadPrices ကို ရေးပါ။ Symbol တစ်ခုစီကို အများဆုံး 120 ms ပဲ ပေးပြီး အဲဒီထက် ကြာရင် ရလဒ်က null ဖြစ်ရပါမယ်။ fetchPrice က symbol အလိုက် နှေးကွေးမှု မတူတဲ့ ဟန်ဆောင် network call ဖြစ်ပါတယ်။

  • loadPrices က coroutineScope ထဲမှာ symbol တစ်ခုစီအတွက် async တစ်ခုစီ စတင်ရမယ်
  • Symbol တစ်ခုစီကို withTimeoutOrNull(120) နဲ့ ဖြတ်ပြီး Map<String, Int?> ပြန်ပေးရမယ်
  • main ထဲမှာ BTC, ETH, DOGE နဲ့ ခေါ်ပြီး map ကို print ထုတ်ပါ
  • check() နဲ့ BTC မှာ စျေးရှိကြောင်းနဲ့ DOGE က null ဖြစ်ကြောင်း အတည်ပြုပါ
PriceBoard.kt
import kotlinx.coroutines.*

// Fake network call: the latency depends on the symbol.
suspend fun fetchPrice(symbol: String): Int {
    val (latencyMs, price) = when (symbol) {
        "BTC" -> 10L to 64_000
        "ETH" -> 40L to 3_200
        else -> 200L to 12
    }
    delay(latencyMs)
    return price
}

// TODO: start one async per symbol inside coroutineScope,
//       wrap each fetch in withTimeoutOrNull(120),
//       then await them all and build the map
suspend fun loadPrices(symbols: List<String>): Map<String, Int?> {
    TODO()
}

fun main() = runBlocking {
    // TODO: call loadPrices(listOf("BTC", "ETH", "DOGE")) and print the result
    // TODO: check() that BTC has a price and DOGE is null
}

ရလဒ်: {BTC=64000, ETH=3200, DOGE=null} ကို print ထုတ်ပါမယ်။ DOGE ရဲ့ fetch က 200 ms ယူတဲ့အတွက် 120 ms မှာ cancel ခံရလို့ null ဖြစ်ပြီး ကျန်နှစ်ခုက အချိန်အတွင်း ပြီးပါတယ်။

အရိပ်အမြွက် ကြည့်ရန်

map နဲ့ symbol တစ်ခုစီကို (symbol to async { ... }) အဖြစ် အရင်စတင်ပါ၊ ပြီးမှ ဒုတိယ အဆင့်မှာ await လုပ်ပြီး associate နဲ့ map ဖွဲ့ပါ။ တစ်ခုချင်း စတင်ပြီး ချက်ချင်း await လုပ်ရင် အလုပ်တွေ ထပ်မနေပါဘူး။ withTimeoutOrNull က အချိန်ကုန်ရင် null ပြန်ပေးတာကို အသုံးပြုပါ။

အဖြေ ကြည့်ရန်
PriceBoard.kt
import kotlinx.coroutines.*

// Fake network call: the latency depends on the symbol.
suspend fun fetchPrice(symbol: String): Int {
    val (latencyMs, price) = when (symbol) {
        "BTC" -> 10L to 64_000
        "ETH" -> 40L to 3_200
        else -> 200L to 12
    }
    delay(latencyMs)
    return price
}

suspend fun loadPrices(symbols: List<String>): Map<String, Int?> = coroutineScope {
    val pending = symbols.map { symbol ->
        symbol to async { withTimeoutOrNull(120) { fetchPrice(symbol) } }
    }
    pending.associate { (symbol, deferred) -> symbol to deferred.await() }
}

fun main() = runBlocking {
    val prices = loadPrices(listOf("BTC", "ETH", "DOGE"))
    println(prices)
    check(prices["BTC"] == 64_000)
    check(prices["DOGE"] == null)
    check(loadPrices(emptyList()).isEmpty())
}

Quick Quiz 1 / 3

ဒီ code က ဘာ print ထုတ်မလဲ? fun main() = runBlocking { launch { delay(100); println("B") }; launch { println("A") }; println("C") }

Quick Quiz 2 / 3

coroutine ထဲက delay() ကို catch (e: Exception) { println(e) } နဲ့ ပတ်ထားတယ်။ ဘာပြဿနာ ရှိလဲ?

Quick Quiz 3 / 3

coroutineScope ထဲမှာ async child သုံးခု ရှိပြီး ဒုတိယတစ်ခုက exception ပစ်တယ်။ coroutineScope ကို try/catch နဲ့ ပတ်ထားရင် ဘာဖြစ်မလဲ?

မှတ်ထားရမယ့် အချက်များ

  • suspend function က thread ကို မပိတ်ဘဲ ခဏရပ်နိုင်ပြီး launch, async, runBlocking တို့က coroutine ကို စတင်ပေးပါတယ်။
  • Structured concurrency မှာ parent က child အားလုံးကို စောင့်၊ cancel လုပ်၊ failure ကို လက်ခံပါတယ်၊ GlobalScope က အဲဒါကို ကျော်သွားပါတယ်။
  • Cancellation က cooperative ဖြစ်ပြီး CancellationException ကို မျိုချမထားဘဲ ပြန် throw ရပါမယ်။
  • coroutineScope မှာ child fail ရင် sibling တွေ cancel ခံရပြီး supervisorScope မှာတော့ child တွေ သီးခြား fail ပါတယ်။
  • Default က CPU အလုပ်အတွက်၊ IO က blocking အလုပ်အတွက်ဖြစ်ပြီး withContext နဲ့ dispatcher ပြောင်းနိုင်ပါတယ်။

Coroutines Basics — Kotlin

Coroutines Basics — Kotlin

နောက်ဆုံးပြင်ဆင်ရက်

Progress ကို ဤ browser (ဤစက်) တွင်သာ သိမ်းထားပါသည်။ အခြားစက်များနှင့် sync မလုပ်ပါ။

ဤသင်ခန်းစာတွင် အမှားတွေ့ပါက အကြောင်းကြားရန်သင့် email app ကို ဤသင်ခန်းစာလိပ်စာ ဖြည့်ပြီးသားဖြင့် ဖွင့်ပေးပါမည် — သင်ကိုယ်တိုင် ပို့မှသာ ပို့မည်ဖြစ်သည်။

Advanced Kotlin Coroutines | Thuta Learning