Weather app with location and offline cache

Build a Compose weather app with coarse location, a city search fallback, Retrofit, a Room cache that works offline, and pull to refresh. About 16 hours.

What you will build

You will build a weather app that opens instantly, even in airplane mode. On first launch it asks for approximate (coarse) location; if the user says no, it offers a city search instead of a dead end. Weather comes from a free public weather API you choose, is parsed with kotlinx.serialization, and is saved in Room. The screen always reads from Room, so the last forecast is shown offline with an "updated at" time, and pull to refresh fetches a new one. The user's Celsius or Fahrenheit choice is stored in Preferences DataStore. The ViewModel exposes one StateFlow of loading, error or content, and you test it with a fake repository. This is a small app, but it shows an employer the habits that matter in real apps: one source of truth, honest error states, permission handling with a fallback, and code you can test without a device.

Skills you practise

  • Jetpack Compose UI with Material 3 and pull to refresh
  • Runtime permissions with a manual fallback
  • Retrofit with kotlinx.serialization
  • Room as an offline cache and single source of truth
  • ViewModel, StateFlow and a sealed UI state
  • Preferences DataStore
  • ViewModel unit tests with fakes

Architecture

The app is a single module with three layers. The data layer has a Retrofit WeatherApi, a Room WeatherDao that exposes Flow<WeatherEntity?>, and a SettingsRepository backed by Preferences DataStore that exposes Flow<TempUnit>. A WeatherRepository interface hides the details: observeWeather() returns the Room Flow, and refresh(query) calls the API and upserts the result into Room with a fetchedAt timestamp. Refresh never returns data to the caller; Room re-emits, and the screen updates from there. Room suspend and Flow queries and Retrofit suspend functions are already main-safe, so the repository does not need withContext(Dispatchers.IO). The presentation layer has a WeatherViewModel that combines the weather Flow, the unit Flow, a refreshing flag and the last error into one WeatherUiState exposed with stateIn. The UI layer collects it with collectAsStateWithLifecycle, wraps the content in a PullToRefreshBox, and handles the location permission. Data flows one way: user action -> ViewModel -> repository -> Room -> Flow back to the UI.

Module or layerResponsibility
UI (Compose)Permission request and city search fallback, pull to refresh, renders WeatherUiState
ViewModelCombines weather, units, refreshing and error into one StateFlow; starts refreshes
RepositoryobserveWeather() from Room, refresh(query) from the API into Room, catches nothing it cannot handle
Data sourcesRetrofit WeatherApi, Room WeatherDao, Preferences DataStore for units, FusedLocationProviderClient for location

Milestones

1. Project setup and screen shell

Create the project and a themed, static weather screen.

  1. Create an Empty Activity (Compose) project and look at where build.gradle.kts, the manifest and local.properties live.
  2. Add the dependencies you will need (Retrofit, the kotlinx.serialization converter, Room with KSP, DataStore Preferences, Lifecycle Compose, Play services location) and sync.
  3. Build a Scaffold with a TopAppBar and a placeholder card showing a hardcoded city and temperature.
  4. Use the generated Material 3 theme for colours and typography.

Done when: The app launches and shows a themed placeholder weather card.

Lessons: android studio project structure, gradle basics and build variants, material 3 theming

2. Networking with Retrofit and kotlinx.serialization

Fetch real weather for fixed coordinates.

  1. Pick a free public weather API. One that needs no key is simplest. Read its docs for the current-weather endpoint and a city search or geocoding endpoint.
  2. Write @Serializable data classes for only the fields you show; set ignoreUnknownKeys = true on your Json instance.
  3. Create a WeatherApi interface with suspend functions and build Retrofit with json.asConverterFactory("application/json".toMediaType()).
  4. If the API needs a key, put it in local.properties (git-ignored by default), read it in Gradle into a buildConfigField, and enable buildFeatures { buildConfig = true }. This keeps it out of Git, not out of the APK, so use it only for a free, low-risk key.
  5. Call the API from a temporary button and log the parsed object.

Done when: Tapping the button logs a parsed weather object, and git status shows no key in any tracked file.

Lessons: retrofit and okhttp, serialization kotlinx vs moshi, storing secrets and the keystore

3. Room cache

Store the latest weather so it survives restarts.

  1. Define a WeatherEntity with a fixed id (the app shows one location), the city name, temperature in Celsius, a description and fetchedAt.
  2. Write a WeatherDao with @Query returning Flow<WeatherEntity?> and an @Upsert suspend fun upsert(entity: WeatherEntity).
  3. Build the database once (an Application-scoped singleton or a simple manual container).
  4. Add mapping functions from the network model to the entity and from the entity to a Weather domain model.

Done when: After one successful fetch, killing the app and reopening it in airplane mode still shows the saved weather.

Lessons: room entities daos queries

4. Offline-first repository

Make Room the only thing the screen reads.

  1. Define a WeatherRepository interface with observeWeather(): Flow<Weather?> and suspend fun refresh(query: LocationQuery).
  2. Implement it: observeWeather() maps the DAO Flow; refresh() calls the API, maps the result and upserts it with fetchedAt = System.currentTimeMillis().
  3. Let refresh() throw on failure (IOException, HttpException, SerializationException); the ViewModel decides how to show it.
  4. Optionally skip a refresh on screen open when fetchedAt is newer than a time-to-live you choose; pull to refresh always fetches.

Done when: The cached weather appears immediately on launch, and a successful refresh updates the screen only through the Room Flow.

Lessons: repository pattern, single source of truth, caching and offline reads

5. ViewModel, UI state and pull to refresh

Expose one state for the screen and wire up refresh.

  1. Create a sealed WeatherUiState with Loading, Error and Content (content carries the weather, the unit, isRefreshing and an optional refresh error).
  2. In WeatherViewModel, combine the repository Flow, the unit Flow, a refreshing flag and the last error, then stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), Loading).
  3. Collect it with collectAsStateWithLifecycle() and render each state: a spinner, a full-screen error with a retry button, or the content with an "updated at" line.
  4. Wrap the content in PullToRefreshBox(isRefreshing = ..., onRefresh = ...). When a refresh fails but cached data exists, keep the content and show a snackbar.

Done when: Pulling down shows the indicator and updates the data online, and offline it keeps the old data and shows an error message.

Lessons: viewmodel and ui state, stateflow and sharedflow, collecting flows safely in the ui, error handling and result types

6. Coarse location with a city search fallback

Use the device's approximate location, or let the user type a city.

  1. Declare only ACCESS_COARSE_LOCATION in the manifest; city-level accuracy is enough for weather.
  2. In Compose, check ContextCompat.checkSelfPermission and, if not granted, launch rememberLauncherForActivityResult(ActivityResultContracts.RequestPermission()).
  3. When granted, get a location with FusedLocationProviderClient.getCurrentLocation(Priority.PRIORITY_BALANCED_POWER_ACCURACY, null) and refresh with those coordinates. Handle a null result by falling back to search.
  4. When denied, show a city search field that calls the API's city search, then refresh with the chosen city. If shouldShowRequestPermissionRationale is false right after a denial, offer a button to the app's settings page instead of asking again.

Done when: Granting permission shows local weather; denying it shows the search field, and a searched city loads and is cached.

Lessons: runtime permissions, side effects launchedeffect and friends

7. Units in Preferences DataStore

Let the user switch between Celsius and Fahrenheit.

  1. Create one preferencesDataStore(name = "settings") delegate at the top level of a file.
  2. Build a SettingsRepository that maps a stringPreferencesKey("unit") to a TempUnit enum, defaulting to Celsius when the key is missing.
  3. Add a toggle in the top bar that calls dataStore.edit { it[UNIT] = unit.name }.
  4. Keep Celsius in Room and convert only for display, so switching units never needs a network call.

Done when: Switching units updates the screen at once and the choice survives an app restart.

Lessons: datastore preferences and proto

8. ViewModel tests with a fake repository

Prove the state logic without a network, database or device.

  1. Write FakeWeatherRepository backed by a MutableStateFlow<Weather?> with a switch to make refresh() throw IOException, and a FakeSettingsRepository.
  2. Add a MainDispatcherRule that calls Dispatchers.setMain and Dispatchers.resetMain.
  3. Because the state uses WhileSubscribed, start a collector in backgroundScope before asserting.
  4. Test three cases: a successful refresh gives Content, a failed refresh with no cache gives Error, and a failed refresh with cache keeps Content with a refresh error.

Done when: All three tests pass with ./gradlew testDebugUnitTest.

Lessons: viewmodel tests, testing coroutines and flows, fakes vs mocks

Key code

The ViewModel combines the cached weather, the unit setting, a refreshing flag and the last error into one state. The repository and settings are interfaces, so the test below swaps in fakes.

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.combine
import kotlinx.coroutines.flow.stateIn
import kotlinx.coroutines.launch
import kotlinx.serialization.SerializationException
import retrofit2.HttpException
import java.io.IOException
 
enum class TempUnit { CELSIUS, FAHRENHEIT }
 
data class Weather(
    val city: String,
    val tempCelsius: Double,
    val description: String,
    val fetchedAt: Long, // shown as "updated at" so stale data is visible
)
 
sealed interface LocationQuery {
    data class Coordinates(val lat: Double, val lon: Double) : LocationQuery
    data class City(val name: String) : LocationQuery
}
 
interface WeatherRepository {
    fun observeWeather(): Flow<Weather?>          // Room Flow
    suspend fun refresh(query: LocationQuery)     // API -> Room; throws on failure
}
 
interface SettingsRepository {
    val unit: Flow<TempUnit>                      // Preferences DataStore
}
 
sealed interface WeatherUiState {
    data object Loading : WeatherUiState
    data class Error(val message: String) : WeatherUiState
    data class Content(
        val weather: Weather,
        val unit: TempUnit,
        val isRefreshing: Boolean,
        val refreshError: String?,
    ) : WeatherUiState
}
 
class WeatherViewModel(
    private val weatherRepository: WeatherRepository,
    settingsRepository: SettingsRepository,
) : ViewModel() {
 
    private val isRefreshing = MutableStateFlow(false)
    private val lastError = MutableStateFlow<String?>(null)
 
    val uiState: StateFlow<WeatherUiState> = combine(
        weatherRepository.observeWeather(),
        settingsRepository.unit,
        isRefreshing,
        lastError,
    ) { weather, unit, refreshing, error ->
        when {
            weather != null -> WeatherUiState.Content(weather, unit, refreshing, error)
            error != null -> WeatherUiState.Error(error)
            else -> WeatherUiState.Loading
        }
    }.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), WeatherUiState.Loading)
 
    fun refresh(query: LocationQuery) {
        if (isRefreshing.value) return
        viewModelScope.launch {
            isRefreshing.value = true
            lastError.value = null
            try {
                weatherRepository.refresh(query) // Room re-emits on success
            } catch (e: IOException) {
                lastError.value = "No connection. Showing the last saved weather."
            } catch (e: HttpException) {
                lastError.value = "The weather service returned ${e.code()}."
            } catch (e: SerializationException) {
                lastError.value = "Unexpected response from the weather service."
            } finally {
                isRefreshing.value = false
            }
        }
    }
}
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.launch
import kotlinx.coroutines.test.StandardTestDispatcher
import kotlinx.coroutines.test.TestDispatcher
import kotlinx.coroutines.test.UnconfinedTestDispatcher
import kotlinx.coroutines.test.advanceUntilIdle
import kotlinx.coroutines.test.resetMain
import kotlinx.coroutines.test.runTest
import kotlinx.coroutines.test.setMain
import org.junit.Assert.assertTrue
import org.junit.Rule
import org.junit.Test
import org.junit.rules.TestWatcher
import org.junit.runner.Description
import java.io.IOException
 
@OptIn(ExperimentalCoroutinesApi::class)
class MainDispatcherRule(
    private val testDispatcher: TestDispatcher = StandardTestDispatcher(),
) : TestWatcher() {
    override fun starting(description: Description) = Dispatchers.setMain(testDispatcher)
    override fun finished(description: Description) = Dispatchers.resetMain()
}
 
class FakeWeatherRepository : WeatherRepository {
    val weather = MutableStateFlow<Weather?>(null)
    var failRefresh = false
    override fun observeWeather(): Flow<Weather?> = weather
    override suspend fun refresh(query: LocationQuery) {
        if (failRefresh) throw IOException("offline")
        weather.value = Weather("Lisbon", 21.0, "Clear", fetchedAt = 0L)
    }
}
 
class FakeSettingsRepository : SettingsRepository {
    override val unit = MutableStateFlow(TempUnit.CELSIUS)
}
 
@OptIn(ExperimentalCoroutinesApi::class)
class WeatherViewModelTest {
    @get:Rule val mainDispatcherRule = MainDispatcherRule()
 
    @Test
    fun failedRefreshWithNoCache_showsError() = runTest {
        val repo = FakeWeatherRepository().apply { failRefresh = true }
        val vm = WeatherViewModel(repo, FakeSettingsRepository())
        backgroundScope.launch(UnconfinedTestDispatcher(testScheduler)) { vm.uiState.collect {} }
 
        vm.refresh(LocationQuery.City("Lisbon"))
        advanceUntilIdle()
 
        assertTrue(vm.uiState.value is WeatherUiState.Error)
    }
 
    @Test
    fun failedRefreshWithCache_keepsContent() = runTest {
        val repo = FakeWeatherRepository()
        repo.weather.value = Weather("Lisbon", 18.0, "Cloudy", fetchedAt = 0L)
        repo.failRefresh = true
        val vm = WeatherViewModel(repo, FakeSettingsRepository())
        backgroundScope.launch(UnconfinedTestDispatcher(testScheduler)) { vm.uiState.collect {} }
 
        vm.refresh(LocationQuery.City("Lisbon"))
        advanceUntilIdle()
 
        val state = vm.uiState.value
        assertTrue(state is WeatherUiState.Content && state.refreshError != null)
    }
}
  • refresh() never pushes data to the UI. It writes to Room, and the observeWeather() Flow re-emits, so there is exactly one path for data to reach the screen.
  • A failed refresh with cached data stays Content with refreshError set (show it in a snackbar); only "no cache and an error" becomes a full-screen Error.
  • Only the expected failures are caught: IOException (no network), HttpException (non-2xx) and SerializationException (bad body). CancellationException is not caught, so leaving the screen cancels cleanly.
  • stateIn(WhileSubscribed(5_000)) keeps the upstream alive through a rotation but stops it when the app is in the background; that is why the test starts a collector in backgroundScope before asserting.

Pitfalls

  • Committing the API key, or treating BuildConfig as secret. A key in a tracked file ends up on GitHub, and a key in BuildConfig can still be read from the APK with jadx. Fix: prefer an API without a key; otherwise keep the key in git-ignored local.properties, use only a free low-risk key, and keep any paid or secret key on a server.
  • Returning API data straight to the UI. The screen then shows one thing while Room holds another, and the offline path breaks. Fix: the repository writes to Room and the UI only observes the Room Flow.
  • Calling getLastLocation() and trusting it. It can return null, for example after a reboot or when location was never requested on the device. Fix: use getCurrentLocation(Priority.PRIORITY_BALANCED_POWER_ACCURACY, null) and fall back to city search when the result is null.
  • A dead end when permission is denied. Without a fallback the app shows nothing. Fix: show city search on denial, and after a permanent denial offer the settings page instead of calling launch() again, which would return denied at once.
  • Replacing content with Loading on every refresh. Pull to refresh then blanks the screen and, offline, swaps good data for an error. Fix: keep Content and drive the indicator with isRefreshing; use full-screen states only when there is no cache.
  • Storing the converted temperature. Saving Fahrenheit or Celsius depending on the setting means a unit change shows wrong values until the next fetch. Fix: store one unit in Room and convert in the UI layer.

Code review finding

Pull to refresh does nothing and old data looks current
  • The repository returned a one-shot flow { } that read the DAO once, fetched, and emitted. The screen never observed Room, so later writes did not reach the UI.
  • The refresh code wrapped everything in catch (e: Exception) { }, so offline refreshes failed silently and the indicator just stopped.
  • The entity had no fetchedAt, so a forecast from two days ago looked identical to a fresh one.
The fix
  • observeWeather() now returns the DAO's Flow<WeatherEntity?> mapped to the domain model, and refresh() only writes to Room.
  • The ViewModel catches IOException, HttpException and SerializationException, stores a message in refreshError, and the screen shows it in a snackbar while keeping the cached content.
  • The entity stores fetchedAt, and the screen shows "updated at" under the temperature.

Stretch goals

  • Add a PeriodicWorkRequest with WorkManager that refreshes the saved location every few hours on an unmetered network.
  • Move construction to Hilt so the ViewModel gets its repositories injected.
  • Save recent searched cities in a second Room table and show them under the search field.
  • Add a daily forecast list with LazyColumn from the API's forecast endpoint, cached the same way.

Done checklist

  • No API key appears in any file tracked by Git.
  • The app shows the last saved weather and its "updated at" time in airplane mode.
  • Denying location shows city search, and a searched city loads and is cached.
  • Pull to refresh shows an indicator, updates the data online, and keeps the old data with a message offline.
  • The unit setting survives a restart and switching it needs no network call.
  • The ViewModel exposes a single StateFlow<WeatherUiState> collected with collectAsStateWithLifecycle().
  • ViewModel tests with fake repositories pass for success, error with no cache, and error with cache.

Talking about it in an interview

  • "Room is the single source of truth. Refresh writes to the database and the screen only observes it, so the app opens offline and there is one path for data to reach the UI."
  • "I asked for coarse location only, because city-level accuracy is enough for weather, and denial falls back to city search so the app still works."
  • "A failed refresh with cached data keeps the content and shows a message; a full-screen error appears only when there is nothing to show. I store fetchedAt so stale data is visible."
  • "The ViewModel depends on repository interfaces, so my tests use fakes backed by MutableStateFlow. They run on the JVM in milliseconds with no network, database or device."