News reader with Retrofit and Hilt

Build an offline-first news reader with Retrofit, kotlinx.serialization, Room, Hilt and Flow, with pull to refresh and MockWebServer tests. About 28 hours.

What you will build

The finished app shows a list of news articles from a public REST API. It stores articles in Room, so the list shows instantly on a cold start, even offline. Pull to refresh fetches new data and writes it into the database. The UI shows loading, error, and empty states. Tapping an article opens a detail screen.

Use any public JSON API that returns a list of items with an id, a title and a date. This page uses a placeholder base URL (https://example.com/api/) and an articles endpoint. You do not need an API key; if the API you pick needs one, keep it out of source control.

This project proves you can wire a full data pipeline: Retrofit for HTTP, kotlinx.serialization for JSON, Room for local storage, Hilt for dependency injection, and coroutines with Flow for async data. It shows you understand the repository pattern, the database as the single source of truth, and how to handle network failures without crashing or blanking the UI.

Skills you practise

  • Retrofit with the kotlinx.serialization converter for typed HTTP calls
  • Room as the single source of truth, with Flow queries and a transactional refresh
  • Hilt modules, @Binds vs @Provides, qualifiers and scopes
  • Coroutines and Flow, with injected dispatchers and correct cancellation
  • One StateFlow<UiState> that covers loading, error, empty and refreshing
  • Material 3 PullToRefreshBox and type-safe Navigation Compose routes
  • MockWebServer tests for the network layer and fake repositories for ViewModel tests

Architecture

The app has three layers. The data layer holds the Retrofit API interface, the @Serializable DTOs, and a Room database with an ArticleEntity and an ArticleDao. A NewsRepository interface and its implementation also live here. The presentation layer has a ViewModel that exposes a StateFlow<NewsUiState> and Compose screens that collect it. A separate domain layer is optional for an app this size; a plain Article model that the UI uses is enough.

Data flows one way. The UI only ever reads from Room: the DAO returns a Flow<List<ArticleEntity>>, the repository maps it to Article, and the ViewModel turns it into UI state. A refresh fetches from the network and writes the result into Room in one transaction. Room then re-emits, and the UI updates. The network result never goes straight to the screen. If the refresh fails, the cached list stays on screen and the UI shows an error message.

Hilt provides OkHttpClient, Retrofit, NewsApi, the database, the DAO and the repository. Retrofit and Room suspend functions are already main-safe, so they need no withContext. An injected @DefaultDispatcher is used only for CPU work such as mapping a large response, and tests can replace it with a test dispatcher.

Module or layerResponsibility
NetworkNewsApi Retrofit interface, @Serializable DTOs, one shared OkHttpClient with logging only in debug builds.
DatabaseNewsDatabase, ArticleEntity, ArticleDao with Flow queries and a @Transaction replace method.
RepositoryNewsRepository interface and OfflineFirstNewsRepository. Exposes Room as a Flow, and refresh() writes the network result into Room.
PresentationNewsViewModel and ArticleViewModel with StateFlow UI state, Compose list and detail screens, pull to refresh.
DIHilt modules in SingletonComponent: @Provides for Retrofit, OkHttp, Room and dispatchers, @Binds for the repository.
TestsMockWebServer for NewsApi and the repository, in-memory Room, a fake repository and StandardTestDispatcher for ViewModel tests.

Milestones

1. Scaffold, Hilt, and a Retrofit call

Create the project, wire Hilt, and make one typed Retrofit call.

  1. Create a new Compose project. Apply the Hilt Gradle plugin, KSP, and org.jetbrains.kotlin.plugin.serialization (same version as your Kotlin plugin).
  2. Add hilt-android (with hilt-compiler through KSP), retrofit, com.squareup.retrofit2:converter-kotlinx-serialization, kotlinx-serialization-json, okhttp, logging-interceptor, and androidx.hilt:hilt-lifecycle-viewmodel-compose.
  3. Add an Application class with @HiltAndroidApp, register it in the manifest, and annotate MainActivity with @AndroidEntryPoint.
  4. Define ArticleDto, ArticlesResponse, and a NewsApi interface with a @GET("articles") suspend fun getArticles().
  5. Write a NetworkModule (@Module, @InstallIn(SingletonComponent::class)) with @Provides @Singleton functions for OkHttpClient, Retrofit and NewsApi. Use json.asConverterFactory("application/json".toMediaType()) and the placeholder base URL. Add HttpLoggingInterceptor only when BuildConfig.DEBUG is true (this needs buildFeatures { buildConfig = true }).
  6. Temporarily inject NewsApi into a @HiltViewModel, get it with hiltViewModel(), call the API in viewModelScope, and log the result.

Done when: The app builds, Hilt injects the NewsApi, and Logcat shows the parsed article list from your chosen API, plus the HTTP log lines in a debug build only.

Lessons: Retrofit and OkHttp, Hilt basics, Serialization: kotlinx vs Moshi, Why dependency injection

2. Room database with Flow queries

Add a Room database that stores articles and emits whenever the table changes.

  1. Define ArticleEntity with @Entity(tableName = "articles") and a @PrimaryKey val id: String.
  2. Write ArticleDao with observeAll(): Flow<List<ArticleEntity>>, observeById(id): Flow<ArticleEntity?>, an @Upsert suspend fun upsertAll(...), a deleteAll() query, and a @Transaction method replaceAll(...) that calls both.
  3. Create NewsDatabase extending RoomDatabase, and add the Room KSP compiler.
  4. Write a DatabaseModule with @Provides @Singleton for the database (Room.databaseBuilder) and a @Provides for the DAO.
  5. Write a DAO test with Room.inMemoryDatabaseBuilder: collect observeAll(), call replaceAll(), and check the new emission. Run it under Robolectric or as an instrumented test.

Done when: The DAO test passes: after replaceAll(), observeAll() emits exactly the new rows, and old rows are gone.

Lessons: Room entities, DAOs and queries, Flow basics: cold streams, Hilt scopes and components

3. Offline-first repository

Build a repository that exposes Room as the single source of truth and refreshes it from the network.

  1. Define NewsRepository with observeArticles(): Flow<List<Article>> and suspend fun refresh(): Result<Unit>.
  2. Implement OfflineFirstNewsRepository with an @Inject constructor taking NewsApi, ArticleDao, and a @DefaultDispatcher CoroutineDispatcher.
  3. observeArticles() maps dao.observeAll() to Article. It never touches the network.
  4. refresh() calls the API, maps DTOs to entities, and calls dao.replaceAll(). Catch only IOException, HttpException and SerializationException, and return Result.failure. Do not use runCatching or catch (e: Exception): they swallow CancellationException.
  5. Define the @DefaultDispatcher qualifier with @Qualifier and provide Dispatchers.Default in a DispatchersModule. Bind the repository with @Binds @Singleton in an abstract DataModule.

Done when: With airplane mode on, a cold start shows the cached list and refresh() returns a failure. With the network back, refresh() updates the rows and the list re-emits.

Lessons: Repository pattern, Single source of truth, Caching and offline reads, Exception handling in coroutines, Dispatchers and threading

4. ViewModel and UI state

Expose one StateFlow<NewsUiState> that covers loading, success, empty, refreshing and error.

  1. Define NewsUiState as a data class: articles, isLoading (no Room emission yet), isRefreshing, and errorMessage (a @StringRes Int?).
  2. Keep isRefreshing and errorMessage in private MutableStateFlows. combine them with repository.observeArticles() and call stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), NewsUiState()).
  3. Add a non-suspend fun refresh() that launches in viewModelScope, ignores a second call while one is running, sets isRefreshing, and sets errorMessage on failure.
  4. Call refresh() from init so the first launch fetches data while the cache is shown.
  5. Treat the error as UI state, not a one-off event: the screen shows it, then calls errorShown(), which clears it.

Done when: A ViewModel test (milestone 6) or a manual run shows each state: spinner on first launch, the list, the empty message, and the error message with the cached list still visible.

Lessons: ViewModel and UI state, StateFlow and SharedFlow, One-off events done right, Collecting flows safely in the UI

5. Compose UI, pull to refresh, and navigation

Render the list, add pull to refresh, and open a detail screen.

  1. Build NewsListScreen. Read state with collectAsStateWithLifecycle() and render a LazyColumn with key = { it.id }.
  2. Wrap the content in Material 3 PullToRefreshBox(isRefreshing = state.isRefreshing, onRefresh = viewModel::refresh). Add @OptIn(ExperimentalMaterial3Api::class) if your Material 3 version still marks it experimental.
  3. Show a centered spinner when the list is empty and loading, the error (or an empty message) with a retry button when it is empty and idle, and a Snackbar for errorMessage when cached rows exist. Put the empty and error content in a vertically scrollable container, so the pull gesture still works there.
  4. Add a NavHost with type-safe routes: @Serializable object ArticleList and @Serializable data class ArticleDetail(val id: String).
  5. In ArticleViewModel, read the id with savedStateHandle.toRoute<ArticleDetail>() and observe dao.observeById(id) through the repository. Get it in the detail screen with hiltViewModel().

Done when: Pulling down shows the indicator until the write finishes and the list updates. Tapping an article opens its detail. Rotating on the detail screen keeps the same article.

Lessons: Lists with LazyColumn, Navigation in Compose, SavedStateHandle and process death, Unidirectional data flow

6. Tests with MockWebServer and fakes

Test the network layer, the repository and the ViewModel.

  1. Add com.squareup.okhttp3:mockwebserver3, kotlinx-coroutines-test, turbine, and Robolectric (or put the Room tests in androidTest).
  2. API test: build NewsApi against server.url("/"), enqueue a JSON body, and assert the parsed DTOs and the request path.
  3. Repository test with in-memory Room: enqueue a JSON response, call refresh(), and assert the rows in the database. Then enqueue a 500 response and assert that refresh() returns a failure and the old rows are still there.
  4. ViewModel test: use a FakeNewsRepository backed by a MutableStateFlow, set Dispatchers.setMain(StandardTestDispatcher()), and assert the uiState sequence for success, empty and failure with Turbine.
  5. Run ./gradlew test (and connectedAndroidTest if you chose instrumented Room tests).

Done when: At least four tests pass: API parsing, refresh success, refresh failure keeps the cache, and a ViewModel state sequence.

Lessons: Testing coroutines and flows, ViewModel tests, Fakes vs mocks, Test pyramid for Android

Key code

@Serializable
data class ArticleDto(val id: String, val title: String, val summary: String = "", val publishedAt: String)
 
@Serializable
data class ArticlesResponse(val articles: List<ArticleDto>)
 
interface NewsApi {
    @GET("articles")
    suspend fun getArticles(): ArticlesResponse
}
 
@Dao
abstract class ArticleDao {
    @Query("SELECT * FROM articles ORDER BY publishedAt DESC")
    abstract fun observeAll(): Flow<List<ArticleEntity>>
 
    @Upsert
    abstract suspend fun upsertAll(articles: List<ArticleEntity>)
 
    @Query("DELETE FROM articles")
    abstract suspend fun deleteAll()
 
    @Transaction
    open suspend fun replaceAll(articles: List<ArticleEntity>) {
        deleteAll()
        upsertAll(articles)
    }
}
 
class OfflineFirstNewsRepository @Inject constructor(
    private val api: NewsApi,
    private val dao: ArticleDao,
    @DefaultDispatcher private val default: CoroutineDispatcher,
) : NewsRepository {
 
    override fun observeArticles(): Flow<List<Article>> =
        dao.observeAll().map { rows -> rows.map(ArticleEntity::toArticle) }
 
    override suspend fun refresh(): Result<Unit> = try {
        val response = api.getArticles() // Retrofit suspend call: already main-safe
        val rows = withContext(default) { response.articles.map(ArticleDto::toEntity) }
        dao.replaceAll(rows) // one transaction: observers never see a half-written table
        Result.success(Unit)
    } catch (e: IOException) {
        Result.failure(e)
    } catch (e: HttpException) {
        Result.failure(e)
    } catch (e: SerializationException) {
        Result.failure(e)
    }
}
 
@Module
@InstallIn(SingletonComponent::class)
abstract class DataModule {
    @Binds
    @Singleton
    abstract fun bindNewsRepository(impl: OfflineFirstNewsRepository): NewsRepository
}
  • @GET goes on the function, not on the interface. Retrofit reads it per method.
  • refresh() catches only network, HTTP and parsing errors. A CancellationException (the user left the screen, the scope was cancelled) still propagates, so the coroutine stops cleanly. runCatching would turn it into a normal failure.
  • replaceAll() runs the delete and the insert in one Room transaction. If the coroutine is cancelled in the middle, the transaction rolls back and the old list stays.
  • The repository has no withContext(Dispatchers.IO), because Retrofit and Room suspend calls already move off the main thread. The injected @DefaultDispatcher is only for the mapping step, and a test can pass a StandardTestDispatcher.
  • @Binds maps the interface to the implementation without writing a factory. Retrofit, OkHttp and Room need @Provides, because their instances come from builders.
@HiltViewModel
class NewsViewModel @Inject constructor(
    private val repository: NewsRepository,
) : ViewModel() {
 
    private val isRefreshing = MutableStateFlow(false)
    private val errorMessage = MutableStateFlow<Int?>(null)
 
    val uiState: StateFlow<NewsUiState> =
        combine(repository.observeArticles(), isRefreshing, errorMessage) { articles, refreshing, error ->
            NewsUiState(articles = articles, isLoading = false, isRefreshing = refreshing, errorMessage = error)
        }.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), NewsUiState(isLoading = true))
 
    init { refresh() }
 
    fun refresh() {
        if (isRefreshing.value) return
        isRefreshing.value = true
        viewModelScope.launch {
            repository.refresh().onFailure { errorMessage.value = R.string.refresh_failed }
            isRefreshing.value = false
        }
    }
 
    fun errorShown() { errorMessage.value = null }
}
  • The list always comes from Room. A failed refresh only adds an error message on top of the cached list.
  • refresh() is a plain function that launches in viewModelScope, so a rotation does not cancel it, and isRefreshing survives in the ViewModel.
  • The error is state that the screen clears with errorShown() after showing it, the same pattern the site uses for one-off events.

Pitfalls

  • Wrapping the refresh in runCatching or catching Exception. It also catches CancellationException. When the user leaves, the coroutine reports a fake failure or keeps working. Fix: catch IOException, HttpException and SerializationException only, or re-throw CancellationException.
  • Showing the network result directly. If the ViewModel puts api.getArticles() into state and also observes Room, two sources fight and the list flickers or goes stale. Fix: the refresh only writes to Room; the UI only reads Room.
  • Not scoping the database or OkHttpClient. Without @Singleton on the @Provides functions, each injection builds a new NewsDatabase or OkHttpClient. Room's change tracking works per database instance, so a write through one instance does not wake a Flow from another, and every new client gets its own connection pool. Fix: @Provides @Singleton for OkHttpClient, Retrofit and the database.
  • Collecting the Room Flow in the Composable. A LaunchedEffect that collects observeAll() restarts on every configuration change and puts data logic in the UI. Fix: the ViewModel exposes a StateFlow with stateIn, and the screen reads it with collectAsStateWithLifecycle().
  • No empty state. When the API returns nothing, the LazyColumn is blank and the user cannot tell an empty result from a broken app. Fix: show a message and a retry button when the list is empty and nothing is loading.
  • Missing the kotlinx.serialization compiler plugin. The @Serializable annotation still resolves, because it comes from the runtime library, but no serializer is generated. The app crashes at runtime with a SerializationException saying the serializer was not found. Fix: apply org.jetbrains.kotlin.plugin.serialization in the module's build.gradle.kts.
  • Logging bodies in release builds. HttpLoggingInterceptor at BODY prints every response, and any headers, to Logcat. Fix: add it only when BuildConfig.DEBUG is true.
  • Launching the refresh from GlobalScope or the screen. GlobalScope is tied to nothing, and a screen scope is cancelled on rotation. Fix: viewModelScope.launch inside the ViewModel, called from a non-suspend refresh().

Code review finding

Pull-to-refresh result is lost on configuration change
  • The screen calls a suspend fun refresh() on the ViewModel from rememberCoroutineScope().launch and keeps isRefreshing in a remember { mutableStateOf(false) }.
  • On rotation, the Activity is recreated and the composition is disposed. The coroutine scope is cancelled, so the network call is cancelled and nothing is written to Room.
  • The new composition starts with isRefreshing = false, so the indicator disappears and the list did not change. The user thinks the refresh worked.
The fix
  • Make refresh() a non-suspend function that launches in viewModelScope. The ViewModel survives configuration changes, so the request and the Room write finish.
  • Keep isRefreshing in the ViewModel's NewsUiState and pass it to PullToRefreshBox, so the indicator survives rotation.
  • Add a ViewModel test with a fake repository that suspends in refresh(). Assert that uiState shows isRefreshing = true, then false with the new list after the fake completes. Check rotation by hand on a device.

Stretch goals

  • Switch the list to Paging 3 with a RemoteMediator that writes pages into Room, and read Room's PagingSource.
  • Add a WorkManager periodic worker (minimum interval 15 minutes) with a network constraint that calls repository.refresh() in the background.
  • Store the last successful refresh time in DataStore and show "Updated 5 min ago". Skip the automatic refresh on launch when the cache is fresh.
  • Use MockWebServer's throttled or delayed responses to test that the loading state stays visible on a slow network.
  • Add a category endpoint, store a category column, and filter the list with a Flow-backed Room query.

Done checklist

  • First launch fetches articles from the network and stores them in Room.
  • Killing the process and relaunching in airplane mode shows the cached list, plus an error message from the failed refresh.
  • Pull to refresh updates the list. The indicator disappears only after the Room write completes, and survives rotation.
  • Loading, error, and empty states are all reachable. The empty state has a retry button.
  • Tapping an article opens a detail screen through a type-safe route, and back returns to the list at the same scroll position.
  • At least four tests pass: API parsing with MockWebServer, refresh success, refresh failure keeps the cache, and a ViewModel state sequence.
  • No runCatching or catch (e: Exception) around suspend calls. HTTP logging appears only in debug builds.
  • ./gradlew assembleDebug and ./gradlew test pass.

Talking about it in an interview

  • Explain why Room is the single source of truth: the UI collects a Flow from the database, never the network response. The refresh writes into Room in one transaction, and Room's change tracking updates the UI. Offline reads come for free.
  • Describe the strategy: show the cache at once, then refresh in the background (stale-while-revalidate). Compare it with fetching on every launch, which wastes data and battery, and with a freshness check (a timestamp in DataStore) that skips refreshes for a few minutes.
  • Talk about error handling: the repository returns Result and catches only I/O, HTTP and parsing errors, so cancellation still works. The ViewModel turns a failure into an error message in UI state, shown on top of the cached list.
  • Mention dispatchers: Retrofit and Room suspend calls are main-safe, so you did not wrap them in withContext(Dispatchers.IO). You injected a dispatcher only for CPU-heavy mapping, which also makes tests deterministic.
  • Explain the Hilt choices: @Provides @Singleton for builder-made objects (OkHttp, Retrofit, Room), @Binds for the repository interface, a qualifier for the dispatcher, and @HiltViewModel with hiltViewModel() in each screen.
  • If asked about scaling: Paging 3 with a RemoteMediator for long lists, WorkManager for background refresh, and separate Gradle modules for network, database and features.