Thuta Learning
ရှာဖွေရန်
AdvancedMobile Developmentintermediate

Dependency Injection (Hilt)

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

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

  • Dependency Injection (Hilt) ကို ကြောက်စရာမလိုအောင် နားလည်မယ်
  • ကိုယ်တိုင် Android Studio/Compose code ကို run ကြည့်တတ်မယ်
  • Real project ထဲမှာ ဒီ concept ကို ချက်ချင်း အသုံးချတတ်မယ်

ခဏလေး ဒီလိုပဲ စဉ်းစားကြည့်

Dependency Injection (DI) ဆိုတာ class တစ်ခုကို 'ကိုယ့်ဒီပန်ဒင့်စီတွေကို ကိုယ်တိုင် create မလုပ်ဘဲ, ပြင်ပက ပေးပို့ခံရတယ်' ဆိုတဲ့ pattern ပါ — testing/maintainability ပိုကောင်းစေပါတယ် (test အတွက် fake dependency ကို inject လို့ရလို့)။ Hilt က Google ရဲ့ official Android DI library ပါ — `@Inject` annotation ကို constructor ပေါ်ထားရုံနဲ့, Hilt က dependency (Retrofit, Room database) ကို automatic create/provide ပေးပါတယ် — manual `Retrofit.Builder()...build()` ကို ViewModel တစ်ခုချင်းစီမှာ ထပ်ခါထပ်ခါ ရေးစရာ မလိုတော့ပါ.

လက်တွေ့ scenario နဲ့ ချိတ်ကြည့်မယ်

`@HiltViewModel class TodoViewModel @Inject constructor(private val dao: TodoDao) : ViewModel() { ... }` လို့ ရေးထားရင် — Hilt က `TodoDao` instance ကို automatic create/inject ပေးပါတယ်, `TodoViewModel()` ကို manual dao parameter ပေးစရာ မလိုတော့ပါ (`viewModel()` Composable function ကနေ တိုက်ရိုက် ရရှိနိုင်ပါတယ်).

အတူတူ ကြည့်မယ်

kotlin
@HiltViewModel
class TodoViewModel @Inject constructor(
    private val dao: TodoDao,
    private val weatherApi: WeatherApi
) : ViewModel() {
    // dao and weatherApi are automatically provided by Hilt —
    // no manual Retrofit.Builder()/Room.databaseBuilder() calls here
}

@Composable
fun TodoScreen(viewModel: TodoViewModel = hiltViewModel()) {
    // ...
}
You should see
TodoViewModel ကို hiltViewModel() ကနေ ရယူရင် dao/weatherApi ကို manual pass မလိုဘဲ ready ဖြစ်နေတာ တွေ့ရမည်။

၅ မိနစ် စမ်းကြည့်

Hilt setup (documentation review — `@HiltAndroidApp`, `@Module`, `@Provides` annotation) ကို ဖတ်ရှုပြီး, `TodoDao`/`WeatherApi` ကို Hilt module အဖြစ် ဘယ်လို provide ရမလဲ ဒီဇိုင်းရေးကြည့်ပါ။

သတိလေးတစ်ချက်

Hilt annotation processing ကြောင့် build time ခဏ ကြာနိုင်ပါတယ် — project အသေးစား (learning project) အတွက် Hilt setup ရဲ့ complexity က overkill ဖြစ်နိုင်တာကို သတိထားပါ။

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

  • `@HiltAndroidApp` annotation ကို Application class ပေါ်မှာ ထည့်ဖို့ မေ့ခြင်း — Hilt setup တစ်ခုလုံး အလုပ်မလုပ်တော့ပါ
  • Small app (screen ၂-၃ ခုပဲရှိ) မှာတောင် Hilt ကို force သုံးခြင်း — dependency နည်းရင် manual injection က ရိုးရှင်းပြီး ပိုသင့်တော်နိုင်ပါတယ်

အခု ကိုယ်တိုင် စမ်းကြည့်

Hilt setup (documentation review — `@HiltAndroidApp`, `@Module`, `@Provides` annotation) ကို ဖတ်ရှုပြီး, `TodoDao`/`WeatherApi` ကို Hilt module အဖြစ် ဘယ်လို provide ရမလဲ ဒီဇိုင်းရေးကြည့်ပါ။

You'll know it worked when: TodoViewModel ကို hiltViewModel() ကနေ ရယူရင် dao/weatherApi ကို manual pass မလိုဘဲ ready ဖြစ်နေတာ တွေ့ရမည်။

Dependency Injection (Hilt) | Thuta Learning