MVVM With Retrofit and Kotlin Coroutines on Android
MVVM with Retrofit and coroutines is the default stack for most Android apps that talk to a REST API, and it is easy to get 80% right. The remaining 20% is where crashes, leaked requests and stuck loading spinners live: a ViewModel collecting a flow on the wrong dispatcher, a repository swallowing a 500, or an interface that returns a raw response body.
This article walks through the structure that holds up in real projects: a thin Retrofit interface, a repository that owns error mapping, a ViewModel that exposes one state object, and a UI that renders it. Expect concrete code shapes and numbers you can sanity-check against your own codebase.
Set up Retrofit so the layers stay clean
Keep the Retrofit interface boring. Each function should be a single suspend function returning your DTO, not a Call, not Response<T> unless you genuinely need headers or status codes. Suspend functions integrate with structured concurrency, so cancelling the ViewModel scope cancels the HTTP call instead of letting OkHttp finish work nobody will read.
Configure OkHttp once in a small module: a connect timeout around 10 seconds, a read timeout of 15-30 seconds for typical JSON, and an interceptor for auth headers and logging in debug builds only. Reusing one OkHttpClient across the app matters more than people think; each new client gets its own connection pool and thread pool, and three or four of them is a measurable memory and latency cost on low-end devices.
Choose the converter deliberately. Moshi with codegen or kotlinx.serialization both handle Kotlin nullability and default values correctly; Gson silently sets missing fields to null and ignores default constructor values, which turns a missing API field into a NullPointerException three screens later. If you are still comparing HTTP clients, the trade-offs between Retrofit and Ktor are worth a read before you commit.
- One OkHttpClient instance for the whole app
- suspend functions, not Call<T>, in the API interface
- Moshi codegen or kotlinx.serialization over Gson
- Logging interceptor only in debug builds
The repository is where errors become meaningful
A common mistake is letting Retrofit exceptions escape into the ViewModel. Wrap calls in a repository that catches IOException, HttpException and serialization errors and returns a sealed result or a domain model with a failure state. This gives you one place to add retry, token refresh or offline caching later, and it keeps the ViewModel free of networking knowledge.
Be specific about what each failure means to the user. A SocketTimeoutException is "check your connection, try again". A 401 is "session expired". A 500 is "something broke on our side". Mapping them at the repository boundary means the UI layer only deals with two or three friendly messages instead of a dozen exception types.
Avoid catch (e: Exception) at the top of every function. It swallows CancellationException, which breaks coroutine cancellation and leaves requests running after the screen is gone. If you need a broad catch, rethrow CancellationException first, or catch the specific types you expect.
ViewModel: one state object, one coroutine scope
Expose a single immutable UI state from the ViewModel: data, isLoading, and an optional error message. The screen then renders one thing, and you stop chasing combinations of three separate LiveData or StateFlow objects that briefly disagree with each other. This also makes Compose and view binding code dramatically simpler.
Launch work in viewModelScope, never in a manually created scope. When the ViewModel clears, pending requests cancel automatically. For one-shot loads, a plain suspend call inside launch is fine. For data that must survive configuration changes and be shared, use StateFlow with stateIn and a sensible sharing policy; repeatOnLifecycle in the UI collects it only while the screen is visible.
Do not inject a Dispatchers.IO reference directly and hardcode it everywhere. Pass a dispatcher or a coroutine context into the ViewModel or use a qualifier so tests can substitute a test dispatcher. Otherwise every ViewModel test needs runBlocking and real threads, which is slow and flaky.
- viewModelScope for all API work
- One data class for UI state
- stateIn with WhileSubscribed(5000) for shared flows
- Inject dispatchers for testability
Threading rules that prevent jank
Retrofit suspend calls already run off the main thread; you do not need withContext(Dispatchers.IO) around them. Adding it is harmless but signals confusion and multiplies the number of contexts in a call chain. Use Dispatchers.IO only for disk or database work you own, such as Room queries that are not already suspend-aware or file reads.
Heavy mapping is the real main-thread risk. Parsing a 2 MB JSON payload from Moshi takes tens of milliseconds; mapping it into UI models with sorting and grouping can take another 20-80 ms depending on list size. Do that work on Default, then hand the finished list to the main thread. Lists above roughly 500 items with per-item formatting are where you will see dropped frames on mid-range hardware.
Coroutine mistakes tend to cluster around scope and dispatcher choices. If you want a checklist of the ones that show up most in code review, the write-up on common coroutine mistakes with numbers is a good companion to this section.
| Concern | Common default | Sensible range | Why it matters |
|---|---|---|---|
| OkHttp connect timeout | 10 s | 5-15 s | Fails fast on dead networks |
| OkHttp read timeout | 10 s | 15-30 s | Large payloads on slow mobile data |
| JSON parse, 2 MB body | 30-60 ms | 20-100 ms | Main-thread blocking if unmapped |
| DTO to UI mapping, 500 items | 40 ms | 20-80 ms | Visible jank above ~16 ms per frame |
| stateIn WhileSubscribed | 5000 ms | 3000-10000 ms | Keeps data across rotation without leaking |
| ViewModel test suite | 1-3 s | under 5 s | Fast feedback for state logic |
Testing the stack without a server
Because the API interface is suspend-based and the repository owns error mapping, tests stay small. Use a fake implementation of the interface for ViewModel tests and a MockWebServer for repository tests that need real HTTP behaviour, including timeouts and malformed JSON. Both run in a few hundred milliseconds per test.
Use kotlinx-coroutines-test with StandardTestDispatcher and advanceUntilIdle rather than delays. Assert on the sequence of emitted states, not just the final one, so a regression where the loading flag never clears gets caught. That single assertion catches more real bugs than most UI tests do.
Sizing the list layer before it hurts
Most MVVM plus Retrofit articles stop at the ViewModel, but the adapter is where users feel the result. If your API returns 200 items and each row inflates a nested layout, you will see jank even with perfect networking. Page the data, keep item layouts shallow, and measure before optimising.
Adding pagination through Paging 3 or a simple manual page counter changes the repository shape, so decide early. Retrofitting paging into a ViewModel that already exposes a full list usually means rewriting the state class and every test around it.
A structure that survives the second feature
Package by feature, not by layer, once you pass roughly five screens. A feature package holding its API interface, repository, ViewModel and screen keeps changes local; a global data package turns every new endpoint into a merge conflict. Keep the Retrofit builder and OkHttp client in a shared core module that features depend on but never modify.
Finally, decide where DTOs end. Mapping network models to domain models at the repository boundary costs a little boilerplate but protects the UI from API changes. For small apps, using the DTO directly is acceptable; past a handful of endpoints, the mapping layer pays for itself within a couple of sprints.
Where the time actually goes
Teams often assume networking dominates. In practice, JSON parsing and model mapping usually cost more than the HTTP round trip on a warm connection, and layout inflation beats both on list-heavy screens. Profiling the whole path, not just the API call, is what moves the frame times.
Key points
- Keep Retrofit interfaces suspend and the repository responsible for error mapping.
- Expose one UI state object and launch everything in viewModelScope.
- Skip withContext(Dispatchers.IO) around Retrofit suspend calls; map heavy data on Default.
- Profile parsing, mapping and adapter binding together, not just the network call.
Flutter Screen Widget and Cost Estimator
Estimate the number of widgets in a screen and a rough development-hour figure from your component counts. Adjust the fields to see how each UI area affects the total effort.
Editor and Flutter contributor
Writes practical Flutter tutorials focused on widgets, layout and animation. Enjoys breaking large UI problems into small, testable pieces and explaining them clearly to beginners.