Weather app with location and offline cache
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,
StateFlowand 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 layer | Responsibility |
|---|---|
| UI (Compose) | Permission request and city search fallback, pull to refresh, renders WeatherUiState |
| ViewModel | Combines weather, units, refreshing and error into one StateFlow; starts refreshes |
| Repository | observeWeather() from Room, refresh(query) from the API into Room, catches nothing it cannot handle |
| Data sources | Retrofit 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.
- Create an Empty Activity (Compose) project and look at where
build.gradle.kts, the manifest andlocal.propertieslive. - Add the dependencies you will need (Retrofit, the kotlinx.serialization converter, Room with KSP, DataStore Preferences, Lifecycle Compose, Play services location) and sync.
- Build a
Scaffoldwith aTopAppBarand a placeholder card showing a hardcoded city and temperature. - 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.
- 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.
- Write
@Serializabledata classes for only the fields you show; setignoreUnknownKeys = trueon yourJsoninstance. - Create a
WeatherApiinterface withsuspendfunctions and build Retrofit withjson.asConverterFactory("application/json".toMediaType()). - If the API needs a key, put it in
local.properties(git-ignored by default), read it in Gradle into abuildConfigField, and enablebuildFeatures { buildConfig = true }. This keeps it out of Git, not out of the APK, so use it only for a free, low-risk key. - 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.
- Define a
WeatherEntitywith a fixed id (the app shows one location), the city name, temperature in Celsius, a description andfetchedAt. - Write a
WeatherDaowith@QueryreturningFlow<WeatherEntity?>and an@Upsert suspend fun upsert(entity: WeatherEntity). - Build the database once (an
Application-scoped singleton or a simple manual container). - Add mapping functions from the network model to the entity and from the entity to a
Weatherdomain 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.
- Define a
WeatherRepositoryinterface withobserveWeather(): Flow<Weather?>andsuspend fun refresh(query: LocationQuery). - Implement it:
observeWeather()maps the DAOFlow;refresh()calls the API, maps the result and upserts it withfetchedAt = System.currentTimeMillis(). - Let
refresh()throw on failure (IOException,HttpException,SerializationException); the ViewModel decides how to show it. - Optionally skip a refresh on screen open when
fetchedAtis 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.
- Create a sealed
WeatherUiStatewithLoading,ErrorandContent(content carries the weather, the unit,isRefreshingand an optional refresh error). - In
WeatherViewModel,combinethe repositoryFlow, the unitFlow, a refreshing flag and the last error, thenstateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), Loading). - 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. - 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.
- Declare only
ACCESS_COARSE_LOCATIONin the manifest; city-level accuracy is enough for weather. - In Compose, check
ContextCompat.checkSelfPermissionand, if not granted, launchrememberLauncherForActivityResult(ActivityResultContracts.RequestPermission()). - When granted, get a location with
FusedLocationProviderClient.getCurrentLocation(Priority.PRIORITY_BALANCED_POWER_ACCURACY, null)and refresh with those coordinates. Handle anullresult by falling back to search. - When denied, show a city search field that calls the API's city search, then refresh with the chosen city. If
shouldShowRequestPermissionRationaleis 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.
- Create one
preferencesDataStore(name = "settings")delegate at the top level of a file. - Build a
SettingsRepositorythat maps astringPreferencesKey("unit")to aTempUnitenum, defaulting to Celsius when the key is missing. - Add a toggle in the top bar that calls
dataStore.edit { it[UNIT] = unit.name }. - 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.
- Write
FakeWeatherRepositorybacked by aMutableStateFlow<Weather?>with a switch to makerefresh()throwIOException, and aFakeSettingsRepository. - Add a
MainDispatcherRulethat callsDispatchers.setMainandDispatchers.resetMain. - Because the state uses
WhileSubscribed, start a collector inbackgroundScopebefore asserting. - Test three cases: a successful refresh gives
Content, a failed refresh with no cache givesError, and a failed refresh with cache keepsContentwith 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 theobserveWeather()Flowre-emits, so there is exactly one path for data to reach the screen.- A failed refresh with cached data stays
ContentwithrefreshErrorset (show it in a snackbar); only "no cache and an error" becomes a full-screenError. - Only the expected failures are caught:
IOException(no network),HttpException(non-2xx) andSerializationException(bad body).CancellationExceptionis 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 inbackgroundScopebefore 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
BuildConfigcan still be read from the APK withjadx. Fix: prefer an API without a key; otherwise keep the key in git-ignoredlocal.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 returnnull, for example after a reboot or when location was never requested on the device. Fix: usegetCurrentLocation(Priority.PRIORITY_BALANCED_POWER_ACCURACY, null)and fall back to city search when the result isnull. - 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
Contentand drive the indicator withisRefreshing; 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
- 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.
observeWeather()now returns the DAO'sFlow<WeatherEntity?>mapped to the domain model, andrefresh()only writes to Room.- The ViewModel catches
IOException,HttpExceptionandSerializationException, stores a message inrefreshError, 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
PeriodicWorkRequestwith 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
LazyColumnfrom 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 withcollectAsStateWithLifecycle(). - 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
fetchedAtso 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."