Thuta Learning
ရှာဖွေရန်
AdvancedProgrammingbeginner

Advanced Kotlin Coroutines

စိတ်လျှော့ပါ။ ဒီခန်းကို စာအုပ်လိုမဟုတ်ဘဲ စကားပြောသလိုပဲ၊ နားလည်လွယ်အောင် ရှင်းပါမယ်။

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

  • Suspending function ရေးရန်
  • launch နှင့် async ကိုခွဲခြားရန်
  • Structured concurrency ကိုနားလည်ရန်

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

Coroutine သည် thread ကို block မလုပ်ဘဲ suspend နှင့် resume လုပ်နိုင်သော computation ဖြစ်သည်။ suspend သည် function က suspend နိုင်ကြောင်းကြေညာပြီး kotlinx.coroutines က launch, async နှင့် dispatcher များပေးသည်။ Child coroutine များကို scope ထဲတွင်ထားခြင်းက cancellation နှင့် error handling ကိုခန့်မှန်းနိုင်စေသည်။

kotlin
import kotlinx.coroutines.*

suspend fun fetchName(): String {
    delay(200)
    return "Mya"
}

suspend fun fetchScore(): Int {
    delay(200)
    return 91
}

suspend fun main() = coroutineScope {
    val name = async { fetchName() }
    val score = async { fetchScore() }
    println("${name.await()}: ${score.await()}")
}
You should see
Mya: 91

လက်တွေ့စမ်းကြည့်ရန်

သီးခြား suspend functions နှစ်ခုကို async ဖြင့်တပြိုင်နက် run ပြီး awaitAll ဖြင့်ရလဒ်စုပါ။

Coroutines BasicsKotlin

ဒီနေရာမှာ လူအများမှားတတ်တယ်

  • Coroutine အတွင်း Thread.sleep သုံးပြီး thread block လုပ်ခြင်း
  • Lifecycle မရှိသော GlobalScope ကိုပုံမှန် app code တွင်သုံးခြင်း

လေ့ကျင့်ခန်း

သီးခြား suspend functions နှစ်ခုကို async ဖြင့်တပြိုင်နက် run ပြီး awaitAll ဖြင့်ရလဒ်စုပါ။

You'll know it worked when: Mya: 91

Advanced Kotlin Coroutines | Thuta Learning