Skip to content
Tutorials Center
My learning

Topics

Lesson 95 of 104 ยท Projects

Project: Weather App

Build a weather app: a Retrofit client, DTO mapping, a repository with a time-based cache, loading and error states, and the location permission flow, with runnable Kotlin stand-ins.

A weather app is a small project with a big lesson inside it: almost everything interesting happens between your screen and a server you do not control. The network is slow, the response can be incomplete, the phone can be offline, and the user may refuse to share their location. A good weather app handles all of that and still shows something useful.

In this project you will build the data pipeline from the server to the screen: a Retrofit service, mapping from network objects (DTOs) to domain objects, a repository that caches results for a few minutes, a UI state with Loading, Success and Error, and the location permission flow. The real code (Retrofit, Compose, the location APIs) is read-only, because the site has no network access for apps and no emulator. The TryIts are plain Kotlin stand-ins on Piston: a fake API that fails in scripted ways, and a repository, presenter and permission model running on a fake clock. This lesson builds on Retrofit and OkHttp, JSON serialization, error handling, the repository pattern and runtime permissions.

What we are building

One screen that shows the current temperature and conditions for the user's location, with these behaviors:

  1. On start, ask for approximate location (with a short explanation). If the user says no, offer a short list of cities instead of a dead end.
  2. Show a progress indicator while loading.
  3. Reuse data fetched in the last ten minutes instead of calling the server again.
  4. If the refresh fails but we have older data, keep showing it with a note, and only show a full error screen when we have nothing.
  5. A Refresh button that forces a new request.
flowchart LR
    Screen["WeatherScreen"] --> VM["WeatherViewModel"]
    VM --> Repo["WeatherRepository<br/>cache with 10 minute lifetime"]
    Repo --> Api["WeatherApi (Retrofit)"]
    Api --> Net(("Network"))
    VM --> Loc["LocationProvider"]

The repository decides between cache and network. The ViewModel decides which state the screen shows.

Step 1: the API and the DTOs

For this project any weather service works. We will use the shape of a free forecast API that needs no key: you pass latitude and longitude and ask for the current values you want. The server's field names (temperature_2m, weather_code) are not Kotlin style, so we map them with @SerialName. All fields are nullable with defaults, because data from the network is untrusted: a missing field should become a controlled error in our code, not a crash inside the converter.

Kotlin
// read-only: real Retrofit and kotlinx.serialization code
@Serializable
data class CurrentDto(
    @SerialName("temperature_2m") val temperature: Double? = null,
    @SerialName("weather_code") val weatherCode: Int? = null,
)

@Serializable
data class ForecastDto(val current: CurrentDto? = null)

interface WeatherApi {
    @GET("v1/forecast")
    suspend fun forecast(
        @Query("latitude") latitude: Double,
        @Query("longitude") longitude: Double,
        @Query("current") current: String = "temperature_2m,weather_code",
    ): ForecastDto
}

val json = Json { ignoreUnknownKeys = true }

val api: WeatherApi = Retrofit.Builder()
    .baseUrl("https://api.open-meteo.com/")
    .client(OkHttpClient.Builder().callTimeout(15, TimeUnit.SECONDS).build())
    .addConverterFactory(json.asConverterFactory("application/json".toMediaType()))
    .build()
    .create(WeatherApi::class.java)

ignoreUnknownKeys = true lets the server add fields without breaking old app versions. The app also needs the INTERNET permission in the manifest, which is a normal permission and is granted at install time.

Step 2: map DTOs to domain models

The UI should show a Weather, not a ForecastDto. The mapper is where we reject incomplete data and translate the server's numeric weather codes into something our UI understands. A table of codes is a simplification (real services define many more), so an unknown code must not crash anything: it maps to UNKNOWN, and a later server change cannot break the app.

The first TryIt puts the API, the mapper and the error handling together. ScriptedApi is a fake service that behaves the way you tell it to. safeCall converts exceptions into typed outcomes, the same boundary function as in the error handling lesson. runBlocking only plays the role of a coroutine scope for the demo.

Kotlin Fake weather API, mapping and typed errors (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Compare the lines. A valid response becomes a Weather. An unknown weather code and a missing code both degrade to Unknown but still show the temperature: showing something is better than failing for a cosmetic field. A missing temperature is different: without it there is nothing useful to show, so it becomes BadData. The 404 is a Client error (our request is wrong, retrying will not help) and the 503 is a Server error (worth retrying later). The last line is the most common one in real life: no connection.

Step 3: a repository with a cache

Calling the server every time the user rotates the phone or returns to the app wastes battery and data, and the weather does not change that fast. The repository keeps the last result together with the time it was fetched. The rules:

  • Fresh (younger than ten minutes): return the cached value, no network call.
  • Stale or missing, or forced refresh: call the server. On success, store and return it.
  • Server call failed, cache exists: return the old value, marked as stale, so the UI can say "Showing data from 25 minutes ago".
  • Server call failed, no cache: return the error.
Kotlin
// read-only: the repository in a real app
class WeatherRepository(
    private val api: WeatherApi,
    private val clock: Clock = Clock.System,    // injectable, so tests control time
) {
    private data class Entry(val weather: Weather, val fetchedAt: Instant)
    private val cache = mutableMapOf<String, Entry>()
    private val mutex = Mutex()

    suspend fun current(place: Place, forceRefresh: Boolean = false): Outcome<Loaded> = mutex.withLock {
        val cached = cache[place.key]
        val now = clock.now()
        if (cached != null && !forceRefresh && now - cached.fetchedAt < 10.minutes) {
            return Outcome.Success(Loaded(cached.weather, cached.fetchedAt, stale = false))
        }
        when (val result = safeCall { api.forecast(place.lat, place.lon).toDomain() }) {
            is Outcome.Success -> {
                cache[place.key] = Entry(result.value, now)
                Outcome.Success(Loaded(result.value, now, stale = false))
            }
            is Outcome.Failure ->
                if (cached != null) Outcome.Success(Loaded(cached.weather, cached.fetchedAt, stale = true))
                else result
        }
    }
}

The Mutex stops two simultaneous calls (for example from two screens) from both hitting the network. In a bigger app you would persist the cache in Room so it survives process death, as in offline-first. The in-memory map is enough to learn the policy.

Step 4: UI state and the location flow

The ViewModel exposes one state that the screen draws. The location permission adds states of its own, because "no location yet" is a normal situation, not an error:

Kotlin
// read-only
sealed interface WeatherUiState {
    data object NeedsLocation : WeatherUiState                       // permission not decided yet
    data class ChooseCity(val cities: List<Place>, val canAskAgain: Boolean) : WeatherUiState
    data object Loading : WeatherUiState
    data class Success(val place: Place, val weather: Weather, val ageMinutes: Int, val stale: Boolean) : WeatherUiState
    data class Failure(val message: String) : WeatherUiState
}

Asking for location uses the same contract as in runtime permissions. Approximate (coarse) location is enough for weather and is far less invasive than precise location, so request only ACCESS_COARSE_LOCATION. Since Android 12 the user can grant approximate only, and the app has to cope with that.

Kotlin
// read-only: Compose side
val launcher = rememberLauncherForActivityResult(ActivityResultContracts.RequestPermission()) { granted ->
    vm.onLocationPermissionResult(granted, canAskAgain = shouldShowRequestPermissionRationale(activity, COARSE))
}

// read-only: getting a location once the permission is granted
suspend fun Context.currentPlace(): Place? {
    val client = LocationServices.getFusedLocationProviderClient(this)
    val location = client.getCurrentLocation(Priority.PRIORITY_BALANCED_POWER_ACCURACY, null).await()
    return location?.let { Place("here", it.latitude, it.longitude) }
}

Never leave the user stuck. If the permission is denied, switch to ChooseCity with a short list or a search box. If the user has denied it permanently, the system dialog will not appear again, so show a button that opens the app's settings page.

Step 5: run the repository and presenter

The second TryIt contains the cache rules, a permission state machine and a presenter that produces the UI state. Time is fake (clock.minutes) so we can move forward without waiting. The API is a scripted fake whose online flag we can flip. We also count network calls to prove the cache works.

Kotlin Weather repository, cache and permission flow (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Read the table of states. After the first load there was one network call. Four minutes later the call count stayed the same: the repository served the cache. At 12 minutes the cache had expired, so a second call happened. Then, offline, the screen did not turn into an error. It kept the 12-minute-old reading and told the user so (the data is 18 minutes old by then). Only the fresh install without any cache ends with the error screen, because there is nothing else to show. Pull-to-refresh offline also keeps the old data instead of wiping it.

Step 6: finishing touches

  • Units and formatting. Convert in the UI layer: store Celsius in the domain, show Fahrenheit for users whose locale prefers it. Use String.format with a Locale, or a formatter that respects the user's language.
  • Icons and accessibility. Pair every weather icon with a contentDescription such as "Rain". Never rely on color alone.
  • Pull to refresh with a Material 3 PullToRefreshBox that calls refresh(force = true).
  • Rotation and process death. Keep the chosen city in SavedStateHandle or DataStore, so the app reopens on the same place.
  • Testing. The repository takes the API and the clock as constructor parameters, so a unit test can script a failure and move time without waiting (testing ViewModels).
  • Secrets. If your weather service needs an API key, remember that anything in the APK can be extracted. Use a restricted key and read the security lesson.

Common mistakes

  • Using DTOs directly in the UI, so a server change ripples through every screen.
  • Making every DTO field non-null and getting a crash on the first incomplete response.
  • Treating "denied location" as the end of the road instead of offering a manual city.
  • Requesting precise location when approximate is enough.
  • Replacing good old data with an error page as soon as one refresh fails.
  • Caching forever (stale weather) or never (a request on every rotation).
  • Swallowing CancellationException inside safeCall.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why are the fields in ForecastDto nullable with default values?

    A converter that hits a missing non-null field can fail unpredictably. Nullable DTO fields let your own mapper decide whether the response is usable.
  2. 2. The refresh fails but the repository has a cached value. What should the UI show?

    Old data is almost always more useful than nothing. Show it, mark it as stale and let the user retry. Use a full error only when there is nothing to show.
  3. 3. Which location permission is enough for a weather app?

    Weather does not need street-level accuracy. Asking only for approximate location respects privacy and is more likely to be granted.
  4. 4. What is the purpose of an unknown weather code mapping to UNKNOWN instead of throwing?

    Servers evolve. Degrading gracefully for cosmetic data keeps old app versions working. Missing essential data such as the temperature is a different matter and becomes an error.
  5. 5. What happens when the user denies the location permission permanently?

    After a permanent denial the system will not show the dialog. The app needs a fallback path (choose a city) and a button that opens the settings page for the user.

Summary

  • The pipeline is Retrofit service, DTOs, a mapper to domain models, a repository with a cache, a ViewModel with a UI state, and a Compose screen.
  • DTO fields are nullable because network data is untrusted; the mapper decides what is essential (temperature) and what can degrade (unknown code).
  • Typed outcomes (Offline, Server, Client, BadData) keep expected failures out of the exception handlers.
  • The repository serves fresh cache, refreshes expired or forced data, and falls back to stale data when the network fails.
  • Location is a state, not an error: ask for approximate location in context, and always offer a manual alternative.
  • The Retrofit and location code is read-only; the TryIts are Kotlin stand-ins with a scripted API and a fake clock.

Next: Project: Expense Tracker