News reader with Retrofit and Hilt
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,
@Bindsvs@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
PullToRefreshBoxand 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 layer | Responsibility |
|---|---|
| Network | NewsApi Retrofit interface, @Serializable DTOs, one shared OkHttpClient with logging only in debug builds. |
| Database | NewsDatabase, ArticleEntity, ArticleDao with Flow queries and a @Transaction replace method. |
| Repository | NewsRepository interface and OfflineFirstNewsRepository. Exposes Room as a Flow, and refresh() writes the network result into Room. |
| Presentation | NewsViewModel and ArticleViewModel with StateFlow UI state, Compose list and detail screens, pull to refresh. |
| DI | Hilt modules in SingletonComponent: @Provides for Retrofit, OkHttp, Room and dispatchers, @Binds for the repository. |
| Tests | MockWebServer 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.
- Create a new Compose project. Apply the Hilt Gradle plugin, KSP, and
org.jetbrains.kotlin.plugin.serialization(same version as your Kotlin plugin). - Add
hilt-android(withhilt-compilerthrough KSP),retrofit,com.squareup.retrofit2:converter-kotlinx-serialization,kotlinx-serialization-json,okhttp,logging-interceptor, andandroidx.hilt:hilt-lifecycle-viewmodel-compose. - Add an
Applicationclass with@HiltAndroidApp, register it in the manifest, and annotateMainActivitywith@AndroidEntryPoint. - Define
ArticleDto,ArticlesResponse, and aNewsApiinterface with a@GET("articles") suspend fun getArticles(). - Write a
NetworkModule(@Module,@InstallIn(SingletonComponent::class)) with@Provides @Singletonfunctions forOkHttpClient,RetrofitandNewsApi. Usejson.asConverterFactory("application/json".toMediaType())and the placeholder base URL. AddHttpLoggingInterceptoronly whenBuildConfig.DEBUGis true (this needsbuildFeatures { buildConfig = true }). - Temporarily inject
NewsApiinto a@HiltViewModel, get it withhiltViewModel(), call the API inviewModelScope, 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.
- Define
ArticleEntitywith@Entity(tableName = "articles")and a@PrimaryKey val id: String. - Write
ArticleDaowithobserveAll(): Flow<List<ArticleEntity>>,observeById(id): Flow<ArticleEntity?>, an@Upsert suspend fun upsertAll(...), adeleteAll()query, and a@TransactionmethodreplaceAll(...)that calls both. - Create
NewsDatabaseextendingRoomDatabase, and add the Room KSP compiler. - Write a
DatabaseModulewith@Provides @Singletonfor the database (Room.databaseBuilder) and a@Providesfor the DAO. - Write a DAO test with
Room.inMemoryDatabaseBuilder: collectobserveAll(), callreplaceAll(), 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.
- Define
NewsRepositorywithobserveArticles(): Flow<List<Article>>andsuspend fun refresh(): Result<Unit>. - Implement
OfflineFirstNewsRepositorywith an@Inject constructortakingNewsApi,ArticleDao, and a@DefaultDispatcher CoroutineDispatcher. observeArticles()mapsdao.observeAll()toArticle. It never touches the network.refresh()calls the API, maps DTOs to entities, and callsdao.replaceAll(). Catch onlyIOException,HttpExceptionandSerializationException, and returnResult.failure. Do not userunCatchingorcatch (e: Exception): they swallowCancellationException.- Define the
@DefaultDispatcherqualifier with@Qualifierand provideDispatchers.Defaultin aDispatchersModule. Bind the repository with@Binds @Singletonin an abstractDataModule.
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.
- Define
NewsUiStateas a data class:articles,isLoading(no Room emission yet),isRefreshing, anderrorMessage(a@StringRes Int?). - Keep
isRefreshinganderrorMessagein privateMutableStateFlows.combinethem withrepository.observeArticles()and callstateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), NewsUiState()). - Add a non-suspend
fun refresh()that launches inviewModelScope, ignores a second call while one is running, setsisRefreshing, and setserrorMessageon failure. - Call
refresh()frominitso the first launch fetches data while the cache is shown. - 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.
- Build
NewsListScreen. Read state withcollectAsStateWithLifecycle()and render aLazyColumnwithkey = { it.id }. - 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. - 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
SnackbarforerrorMessagewhen cached rows exist. Put the empty and error content in a vertically scrollable container, so the pull gesture still works there. - Add a
NavHostwith type-safe routes:@Serializable object ArticleListand@Serializable data class ArticleDetail(val id: String). - In
ArticleViewModel, read the id withsavedStateHandle.toRoute<ArticleDetail>()and observedao.observeById(id)through the repository. Get it in the detail screen withhiltViewModel().
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.
- Add
com.squareup.okhttp3:mockwebserver3,kotlinx-coroutines-test,turbine, and Robolectric (or put the Room tests inandroidTest). - API test: build
NewsApiagainstserver.url("/"), enqueue a JSON body, and assert the parsed DTOs and the request path. - 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 thatrefresh()returns a failure and the old rows are still there. - ViewModel test: use a
FakeNewsRepositorybacked by aMutableStateFlow, setDispatchers.setMain(StandardTestDispatcher()), and assert theuiStatesequence for success, empty and failure with Turbine. - Run
./gradlew test(andconnectedAndroidTestif 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
}@GETgoes on the function, not on the interface. Retrofit reads it per method.refresh()catches only network, HTTP and parsing errors. ACancellationException(the user left the screen, the scope was cancelled) still propagates, so the coroutine stops cleanly.runCatchingwould 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@DefaultDispatcheris only for the mapping step, and a test can pass aStandardTestDispatcher. @Bindsmaps 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 inviewModelScope, so a rotation does not cancel it, andisRefreshingsurvives in theViewModel.- 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: catchIOException,HttpExceptionandSerializationExceptiononly, or re-throwCancellationException. - 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
@Singletonon the@Providesfunctions, each injection builds a newNewsDatabaseorOkHttpClient. Room's change tracking works per database instance, so a write through one instance does not wake aFlowfrom another, and every new client gets its own connection pool. Fix:@Provides @SingletonforOkHttpClient,Retrofitand the database. - Collecting the Room Flow in the Composable. A
LaunchedEffectthat collectsobserveAll()restarts on every configuration change and puts data logic in the UI. Fix: theViewModelexposes aStateFlowwithstateIn, and the screen reads it withcollectAsStateWithLifecycle(). - No empty state. When the API returns nothing, the
LazyColumnis 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
@Serializableannotation still resolves, because it comes from the runtime library, but no serializer is generated. The app crashes at runtime with aSerializationExceptionsaying the serializer was not found. Fix: applyorg.jetbrains.kotlin.plugin.serializationin the module'sbuild.gradle.kts. - Logging bodies in release builds.
HttpLoggingInterceptoratBODYprints every response, and any headers, to Logcat. Fix: add it only whenBuildConfig.DEBUGis true. - Launching the refresh from GlobalScope or the screen.
GlobalScopeis tied to nothing, and a screen scope is cancelled on rotation. Fix:viewModelScope.launchinside theViewModel, called from a non-suspendrefresh().
Code review finding
- The screen calls a
suspend fun refresh()on theViewModelfromrememberCoroutineScope().launchand keepsisRefreshingin aremember { 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.
- Make
refresh()a non-suspend function that launches inviewModelScope. TheViewModelsurvives configuration changes, so the request and the Room write finish. - Keep
isRefreshingin theViewModel'sNewsUiStateand pass it toPullToRefreshBox, so the indicator survives rotation. - Add a ViewModel test with a fake repository that suspends in
refresh(). Assert thatuiStateshowsisRefreshing = 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 3with aRemoteMediatorthat writes pages into Room, and read Room'sPagingSource. - Add a
WorkManagerperiodic worker (minimum interval 15 minutes) with a network constraint that callsrepository.refresh()in the background. - Store the last successful refresh time in
DataStoreand 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
runCatchingorcatch (e: Exception)around suspend calls. HTTP logging appears only in debug builds. ./gradlew assembleDebugand./gradlew testpass.
Talking about it in an interview
- Explain why
Roomis the single source of truth: the UI collects aFlowfrom 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
Resultand catches only I/O, HTTP and parsing errors, so cancellation still works. TheViewModelturns 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 @Singletonfor builder-made objects (OkHttp, Retrofit, Room),@Bindsfor the repository interface, a qualifier for the dispatcher, and@HiltViewModelwithhiltViewModel()in each screen. - If asked about scaling:
Paging 3with aRemoteMediatorfor long lists,WorkManagerfor background refresh, and separate Gradle modules for network, database and features.