Thuta Learning
AdvancedMobile Developmentintermediate

Networking (Retrofit)

Relax. We'll talk through this in plain words — no textbook voice.

What you'll walk away with

  • Understand Networking (Retrofit) without the intimidation
  • Get comfortable running Android Studio/Compose code yourself
  • Apply this concept in a real project right away

Let's think about it this way for a second

Retrofit is the most widely used library for making REST API calls on Android — just declare the API endpoint (URL, HTTP method) as a Kotlin interface (using annotations), and Retrofit handles the HTTP request/response for you, auto-converting the JSON response into a Kotlin data class (via a Gson/Moshi converter). Since API calls depend on the network, they need to be asynchronous — that's where Kotlin Coroutines (next lesson) come in.

Let's connect this to a real scenario

Define `interface WeatherApi { @GET("weather") suspend fun getWeather(@Query("city") city: String): WeatherResponse }`, then `retrofit.create(WeatherApi::class.java)` auto-generates the implementation for you — calling `viewModelScope.launch { val weather = api.getWeather("Yangon") }` fetches the weather data from the API and lets you show it in the UI.

Let's walk through it together

kotlin
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)
You should see
$ val weather = weatherApi.getWeather("Yangon")
// weather: WeatherResponse(city="Yangon", tempCelsius=32.0)

5-minute try-it

Define a `WeatherApi` interface yourself (pick any free public weather API) — build a Retrofit instance and sketch out an API call (review the docs, do a dry run).

A quick word of caution

If you hardcode an API key (secret) into your app code and it ends up in the APK, it can be extracted by decompiling — sensitive keys should be used through a backend proxy server instead.

Easy traps

  • Running a network call directly on the main (UI) thread — this can freeze/crash the app (NetworkOnMainThreadException); you avoid this by using suspend functions + Coroutines
  • Only handling the success case of an API call and skipping error/failure handling (network down, timeout) — a production app needs try/catch or a Result wrapper

Now try it yourself

Define a `WeatherApi` interface yourself (pick any free public weather API) — build a Retrofit instance and sketch out an API call (review the docs, do a dry run).

You'll know it worked when: $ val weather = weatherApi.getWeather("Yangon") // weather: WeatherResponse(city="Yangon", tempCelsius=32.0)

Networking (Retrofit) | Thuta Learning