ခဏလေး ဒီလိုပဲ စဉ်းစားကြည့်
Retrofit က Android မှာ REST API call လုပ်ဖို့ အသုံးအများဆုံး library ပါ — API endpoint (URL, HTTP method) ကို Kotlin interface အနေနဲ့ declare လုပ်ရုံနဲ့ (annotation ဖြင့်), Retrofit က HTTP request/response ကို ကိုင်တွယ်ပေးပါတယ်၊ JSON response ကို Kotlin data class အဖြစ်ပါ auto-convert ပေးပါတယ် (Gson/Moshi converter ဖြင့်)။ API call တွေက network ကို depend ပါတယ်ဆိုတော့ asynchronous ဖြစ်ရပါတယ် — Kotlin Coroutines (နောက် lesson) နဲ့ တွဲသုံးပါတယ်.
လက်တွေ့ scenario နဲ့ ချိတ်ကြည့်မယ်
`interface WeatherApi { @GET("weather") suspend fun getWeather(@Query("city") city: String): WeatherResponse }` လို့ define လုပ်ပြီး, `retrofit.create(WeatherApi::class.java)` နဲ့ implementation ကို auto-generate ပေးပါတယ် — `viewModelScope.launch { val weather = api.getWeather("Yangon") }` လို့ ခေါ်ရင် API ကနေ weather data ကို fetch ယူပြီး UI ထဲ ပြပေးနိုင်ပါတယ်.
အတူတူ ကြည့်မယ်
data class WeatherResponse(val city: String, val tempCelsius: Double)
interface WeatherApi {
@GET("weather")
suspend fun getWeather(@Query("city") city: String): WeatherResponse
}
val retrofit = Retrofit.Builder()
.baseUrl("https://api.example.com/")
.addConverterFactory(GsonConverterFactory.create())
.build()
val weatherApi = retrofit.create(WeatherApi::class.java)$ val weather = weatherApi.getWeather("Yangon")
// weather: WeatherResponse(city="Yangon", tempCelsius=32.0)၅ မိနစ် စမ်းကြည့်
`WeatherApi` interface ကို ကိုယ်တိုင် define လုပ်ကြည့်ပါ (public free weather API တစ်ခုကို ရွေးချယ်ပြီး) — Retrofit instance ဆောက်ပြီး API call တစ်ခု (documentation review, dry-run) ကို ဒီဇိုင်းရေးကြည့်ပါ။
သတိလေးတစ်ချက်
API key (secret) ကို app code ထဲ hardcode ရေးထားပြီး APK ထဲ ပါသွားရင်, decompile လုပ်ပြီး key ကို ထုတ်ယူနိုင်ပါတယ် — sensitive key ကို backend proxy server ကနေတစ်ဆင့် သုံးသင့်ပါတယ်။