<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Adrian Leyva on Medium]]></title>
        <description><![CDATA[Stories by Adrian Leyva on Medium]]></description>
        <link>https://medium.com/@aleyvaschz?source=rss-cdc9b9b616bb------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*qXBtN-UV3vnzL6VbmN02UA@2x.jpeg</url>
            <title>Stories by Adrian Leyva on Medium</title>
            <link>https://medium.com/@aleyvaschz?source=rss-cdc9b9b616bb------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 17 Nov 2026 01:13:30 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@aleyvaschz/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[The Contract You Never Wrote — Dependency Inversion in Android]]></title>
            <link>https://medium.com/@aleyvaschz/the-contract-you-never-wrote-dependency-inversion-in-android-8f0cc06afd76?source=rss-cdc9b9b616bb------2</link>
            <guid isPermaLink="false">https://medium.com/p/8f0cc06afd76</guid>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[clean-code]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[software-architecture]]></category>
            <dc:creator><![CDATA[Adrian Leyva]]></dc:creator>
            <pubDate>Fri, 04 Sep 2026 20:10:10 GMT</pubDate>
            <atom:updated>2026-09-04T20:10:10.371Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*P_WHTnueRzbPVukuQ1ON1Q.jpeg" /></figure><blockquote>Reverse the dependency, keep control.</blockquote><p>Every Android codebase is held together by contracts, even the ones nobody ever sat down to write. When your ViewModel calls a repository, it is agreeing to a set of terms. When that repository calls Retrofit, it accepts another set of terms. Most of these agreements are never negotiated. They are simply inherited from whatever library happened to be in the room when the code was written. We build entire applications on borrowed terms and rarely stop to ask a simple question. Who actually holds the pen.</p><p>Dependency Inversion is the principle that puts the pen back in your hands. It is the D in SOLID, and it is comfortably the most misunderstood letter of the five. People confuse it with a framework, they confuse it with annotations, they confuse it with Hilt. None of that is the principle. The principle is quieter and far more powerful than any library. Once you truly understand it, you start to notice which parts of your code are writing their own terms and which parts are meekly signing whatever the framework slides across the table. That awareness changes how you build software.</p><h3>What The Principle Actually Says</h3><p>Robert Martin phrased Dependency Inversion in two short sentences.</p><blockquote>High level modules should not depend on low level modules, and both should depend on abstractions. Abstractions should not depend on details, and details should depend on abstractions.</blockquote><p>Read that a second time and notice the word carrying all the weight. Abstractions. The principle is not asking you to remove dependencies, because software without dependencies accomplishes nothing. It is asking you to change what your important code leans on. Instead of your business logic depending on a specific database, a specific network client, or a specific framework class, it should depend on an interface that describes intent. The concrete tool then conforms to that interface rather than the other way around. In plain terms, your logic writes the contract, and the details agree to it.</p><p>On Android this matters enormously, because the platform is relentless about pulling your code toward its own classes. Cursors, Room DAOs, Retrofit services, SharedPreferences, WorkManager, and a hundred other types all invite you to depend on them directly. Every time you accept one of those invitations, a piece of your logic becomes bound to terms you did not write and cannot control.</p><h3>The Borrowed Contract</h3><p>Here is the version almost everyone writes first. A ViewModel that talks straight to a concrete repository, which in turn talks straight to Retrofit.</p><pre>class UserRepository(<br>    private val api: UserApiService<br>) {<br>    suspend fun getUser(id: String): User {<br>        return api.fetchUser(id).toDomain()<br>    }<br>}</pre><pre>class ProfileViewModel(<br>    private val repository: UserRepository<br>) : ViewModel() {<br>    private val _state = MutableStateFlow&lt;ProfileState&gt;(ProfileState.Loading)<br>    val state = _state.asStateFlow()<br>    fun load(id: String) {<br>        viewModelScope.launch {<br>            _state.value = ProfileState.Success(repository.getUser(id))<br>        }<br>    }<br>}</pre><p>Nothing here throws an error. It compiles, it runs, it ships. The problem stays invisible until the day you need to change something. Your ProfileViewModel, which holds real presentation logic, now depends on a concrete UserRepository, which itself depends on Retrofit. Your most valuable code has quietly signed a contract that reaches all the way down into a networking library. If you want to test the ViewModel, you drag that entire chain into the test. If you want to swap the network for a local cache, you edit the class that should never have cared where data comes from in the first place.</p><h3>Writing Your Own Terms</h3><p>Now watch what happens when we introduce an abstraction and let ownership shift. The decisive move is choosing who defines the contract. The consumer defines it, not the provider.</p><pre>// Domain layer. Pure Kotlin, no Android, no Retrofit.<br>interface UserRepository {<br>    suspend fun getUser(id: String): User<br>}</pre><pre>class GetUserProfile(<br>    private val repository: UserRepository<br>) {<br>    suspend operator fun invoke(id: String): User = repository.getUser(id)<br>}</pre><p>The domain now owns the UserRepository interface. It describes what the application needs in language the business understands. It says nothing about JSON, endpoints, or suspend cancellation semantics. The data layer arrives later and offers an implementation that honors this contract.</p><pre>// Data layer. This is where the framework details live.<br>class UserRepositoryImpl(<br>    private val api: UserApiService,<br>    private val dao: UserDao<br>) : UserRepository {<br><br>    override suspend fun getUser(id: String): User {<br>            val cached = dao.findById(id)<br>            if (cached != null) return cached.toDomain()<br>            val remote = api.fetchUser(id).toDomain()<br>            dao.insert(remote.toEntity())<br>            return remote<br>        }<br>}</pre><p>Look carefully at who depends on whom now. UserRepositoryImpl conforms to the domain interface. The domain depends on nothing outside itself. Retrofit and Room live entirely inside the data layer, sealed away from the logic that matters. The concrete detail bends to the abstraction, exactly as the principle promised. The domain wrote the terms, and the framework signed them. That is the inversion, and it protects the heart of the application from the constant churn at its edges.</p><h3>Where Hilt Fits, And Where It Does Not</h3><p>This is the moment where many developers reach for Hilt and assume the annotations are the principle. They are not. Hilt is a delivery mechanism. It answers the question of how the concrete implementation reaches the place that needs it, but the inversion already happened the instant we let the domain own the interface. You could wire this by hand in a factory and the architecture would be identical.</p><p>That said, Hilt makes the wiring pleasant, so here is how the binding looks.</p><pre>@Module<br>@InstallIn(SingletonComponent::class)<br>abstract class RepositoryModule {<br>  @Binds<br>      abstract fun bindUserRepository(<br>          impl: UserRepositoryImpl<br>      ): UserRepository<br>}</pre><p>The @Binds function is the seam. It tells the graph that whenever something asks for the UserRepository abstraction, it should receive the concrete UserRepositoryImpl. Your ViewModel and your use case never learn that name. They ask for the interface and remain blissfully ignorant of whatever shows up.</p><pre>@HiltViewModel<br>class ProfileViewModel @Inject constructor(<br>    private val getUserProfile: GetUserProfile<br>) : ViewModel()</pre><p>Notice that the ViewModel depends on a use case, the use case depends on an interface, and the interface belongs to the domain. Not a single line in this class knows that Retrofit exists. That ignorance is the entire point. It is what keeps the class stable while everything beneath it is free to change.</p><h3>Why Your Tests Suddenly Get Easier</h3><p>The clearest payoff of inversion shows up in testing, and it is dramatic. Because the domain speaks only in abstractions, a test can hand it a fake with no framework anywhere in sight.</p><pre>class FakeUserRepository(<br>    private val user: User<br>) : UserRepository {<br>    override suspend fun getUser(id: String): User = user<br>}<br><br>@Test<br>fun `use case returns the user from the repository`() = runTest {<br>    val expected = User(id = &quot;1&quot;, name = &quot;Ada&quot;)<br>    val useCase = GetUserProfile(FakeUserRepository(expected))<br><br>    val result = useCase(&quot;1&quot;)<br><br>    assertEquals(expected, result)<br>}</pre><p>No Robolectric, no MockWebServer, no in memory Room database, no waiting on threads. The test runs in milliseconds because it never touches a real detail. This speed is not a lucky bonus. It is the direct consequence of pointing your logic at an abstraction that any object can satisfy, including a three line fake written for a single test.</p><h3>Conclusion</h3><p>Dependency Inversion is not about adding a library or scattering annotations across your classes. It is about noticing which parts of your code write their own terms and which parts sign whatever the framework hands them. When your important code depends on abstractions it defines, the platform loses its grip on your logic. Retrofit becomes swappable, Room becomes an implementation detail, and your tests run without ceremony because nothing at the core knows or cares how data actually arrives.</p><p>The next time you write a ViewModel that reaches straight into a concrete class, pause and ask who wrote the contract it is living by. If the answer is a networking library or a persistence framework, you have handed away control of your own architecture. Take the pen back. Let your domain define the terms and let the details conform to them. That one habit is the difference between an app that breaks with every change and one that scales.</p><p>Thanks for reading!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8f0cc06afd76" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Shared ViewModels in Android — Managing Shared State Across Screens]]></title>
            <link>https://medium.com/@aleyvaschz/shared-viewmodels-in-android-managing-shared-state-across-screens-b8dc5c0e3ea9?source=rss-cdc9b9b616bb------2</link>
            <guid isPermaLink="false">https://medium.com/p/b8dc5c0e3ea9</guid>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[jetpack-compose]]></category>
            <category><![CDATA[state-management]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Adrian Leyva]]></dc:creator>
            <pubDate>Mon, 17 Aug 2026 15:01:04 GMT</pubDate>
            <atom:updated>2026-08-17T15:01:04.537Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4FNIpuLtj82ThE1UVBWKXw.jpeg" /></figure><blockquote>A practical guide to scoping state between fragments and composables using activity, navigation graph, and back stack scopes.</blockquote><p>Every Android developer eventually hits the same wall. You have two screens that need to talk to each other. A checkout flow where the address screen must know what the cart screen selected. A multi-step onboarding wizard where step three depends on answers from step one. A master-detail layout where tapping an item in the list updates a panel that lives somewhere else entirely.</p><p>The naive reactions are all traps. You pass data through navigation arguments and end up serializing large objects into your back stack. You reach for a singleton or an object holding mutable state and quietly introduce a memory leak that outlives every screen that used it. You bubble callbacks up through three layers of parent components until your code reads like a game of telephone.</p><p>There is a cleaner answer that has been part of the Android toolkit for years and works just as well in Compose as it did with Fragments, the shared ViewModel. The idea is simple, but getting the scope right is where most implementations go wrong. This article walks through what a shared ViewModel actually is, how scoping decides its lifetime, and how to implement it correctly across Fragments, navigation graphs, and Jetpack Compose.</p><h3>What “shared” really means</h3><p>A ViewModel is not inherently shared or private. What makes it one or the other is its scope, meaning the lifecycle owner it is tied to. When you request a ViewModel, the framework looks up a ViewModelStore associated with some owner, and returns the existing instance if one already lives there or creates a new one if it does not.</p><p>If two screens ask for a ViewModel from the same store, they get the same instance. That is the entire mechanism. Sharing is not a special class or annotation. It is two consumers resolving to one store.</p><p>This is why scoping is the whole game. Scope too widely, for example to the Activity, and your ViewModel survives long after the flow that needed it has ended, holding onto stale state. Scope too narrowly, to a single screen, and you are back to having no sharing at all. The right scope is the smallest lifecycle that still contains every screen that needs the shared state.</p><h3>Why not just use a singleton?</h3><p>Before looking at the correct approach, it is worth being explicit about why the tempting shortcut fails.</p><p>A singleton object holding mutable state has no lifecycle awareness. It is created when first touched and never destroyed. State written during a checkout flow is still sitting there the next time the user opens an unrelated screen. Worse, it holds references that the garbage collector cannot reclaim, and if you ever store a Context or a view in it, you have a memory leak.</p><p>A ViewModel solves exactly this. It is bound to a ViewModelStore, and when that store&#39;s owner is permanently destroyed, the framework calls onCleared() and the instance is released. You get shared state with a defined beginning and end, and the coroutines you launch in viewModelScope are cancelled automatically when the scope dies. That automatic cleanup is the reason a shared ViewModel beats any hand-rolled state holder.</p><h3>A multi-step form</h3><p>The clearest example is a form split across several screens. Imagine a registration flow with three steps: account details, profile information, and a confirmation summary. Each step is a separate destination, but they all contribute to a single object that gets submitted at the end.</p><p>Here is the shared ViewModel that holds the accumulated state.</p><pre>data class RegistrationState(<br>    val email: String = &quot;&quot;,<br>    val password: String = &quot;&quot;,<br>    val displayName: String = &quot;&quot;,<br>    val country: String = &quot;&quot;,<br>    val acceptedTerms: Boolean = false<br>)<br><br>class RegistrationViewModel : ViewModel() {<br><br>    private val _state = MutableStateFlow(RegistrationState())<br>    val state: StateFlow&lt;RegistrationState&gt; = _state.asStateFlow()<br><br>    fun updateAccount(email: String, password: String) {<br>        _state.update { it.copy(email = email, password = password) }<br>    }<br><br>    fun updateProfile(displayName: String, country: String) {<br>        _state.update { it.copy(displayName = displayName, country = country) }<br>    }<br><br>    fun setTermsAccepted(accepted: Boolean) {<br>        _state.update { it.copy(acceptedTerms = accepted) }<br>    }<br><br>    fun submit() {<br>        viewModelScope.launch {<br>            // Persist or send state.value to your repository.<br>        }<br>    }<br>}</pre><p>Every step reads from and writes to the same RegistrationState. The question is only how each screen gets the same instance.</p><h3>Sharing with Fragments</h3><p>If you are still on a Fragment-based architecture, there are two scopes worth knowing.</p><p>The broadest is the Activity scope. Using activityViewModels(), every Fragment hosted by the same Activity resolves to a single instance.</p><pre>class AccountStepFragment : Fragment() {<br><br>    private val viewModel: RegistrationViewModel by activityViewModels()<br><br>    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {<br>        super.onViewCreated(view, savedInstanceState)<br>        binding.nextButton.setOnClickListener {<br>            viewModel.updateAccount(<br>                email = binding.emailField.text.toString(),<br>                password = binding.passwordField.text.toString()<br>            )<br>            findNavController().navigate(R.id.action_account_to_profile)<br>        }<br>    }<br>}</pre><p>The confirmation step reads the same state without any of the values being passed through navigation arguments.</p><pre>class ConfirmationFragment : Fragment() {<br><br>    private val viewModel: RegistrationViewModel by activityViewModels()<br><br>    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {<br>        super.onViewCreated(view, savedInstanceState)<br>        viewLifecycleOwner.lifecycleScope.launch {<br>            viewLifecycleOwner.repeatOnLifecycle(Lifecycle.State.STARTED) {<br>                viewModel.state.collect { state -&gt;<br>                    binding.summaryEmail.text = state.email<br>                    binding.summaryName.text = state.displayName<br>                }<br>            }<br>        }<br>    }<br>}</pre><p>The problem with Activity scope is that the ViewModel lives as long as the Activity does. If the same Activity hosts unrelated screens, the registration state lingers after the flow completes. For a self-contained flow, the better fit is a navigation graph scope.</p><p>By wrapping the three steps in a nested navigation graph and using navGraphViewModels(), the ViewModel is created when the user enters the graph and cleared the moment they leave it.</p><pre>class ProfileStepFragment : Fragment() {<br><br>    private val viewModel: RegistrationViewModel by navGraphViewModels(R.id.registration_graph)<br><br>    // Same instance as the other fragments inside registration_graph,<br>    // but destroyed as soon as the user pops out of the graph.<br>}</pre><p>This is the sweet spot for flows. The lifetime matches the feature exactly, so there is no stale state and no leak.</p><h3>Sharing in Jetpack Compose</h3><p>Compose changes the syntax but not the underlying idea. You still resolve a ViewModel from a store, and the store you pick decides the scope.</p><p>For screens inside a NavHost, the cleanest approach scopes the ViewModel to a navigation graph route. You obtain the back stack entry for that route and use it as the ViewModelStoreOwner. Every destination inside the graph then shares the instance.</p><pre>@Composable<br>private fun sharedRegistrationViewModel(<br>    navController: NavController,<br>    backStackEntry: NavBackStackEntry<br>): RegistrationViewModel {<br>    val parentEntry = remember(backStackEntry) {<br>        navController.getBackStackEntry(&quot;registration_graph&quot;)<br>    }<br>    return hiltViewModel(parentEntry)<br>}</pre><p>Wiring it into the graph looks like this. Notice that each screen calls the helper above, so all three resolve to the same ViewModel bound to the registration_graph entry.</p><pre>NavHost(navController, startDestination = &quot;registration_graph&quot;) {<br>    navigation(<br>        startDestination = &quot;account&quot;,<br>        route = &quot;registration_graph&quot;<br>    ) {<br>        composable(&quot;account&quot;) { entry -&gt;<br>            val viewModel = sharedRegistrationViewModel(navController, entry)<br>            AccountScreen(<br>                viewModel = viewModel,<br>                onNext = { navController.navigate(&quot;profile&quot;) }<br>            )<br>        }<br>        composable(&quot;profile&quot;) { entry -&gt;<br>            val viewModel = sharedRegistrationViewModel(navController, entry)<br>            ProfileScreen(<br>                viewModel = viewModel,<br>                onNext = { navController.navigate(&quot;confirmation&quot;) }<br>            )<br>        }<br>        composable(&quot;confirmation&quot;) { entry -&gt;<br>            val viewModel = sharedRegistrationViewModel(navController, entry)<br>            ConfirmationScreen(<br>                viewModel = viewModel,<br>                onSubmit = { viewModel.submit() }<br>            )<br>        }<br>    }<br>}</pre><p>Each screen collects state the idiomatic Compose way and stays free of any knowledge about how the other screens produced it.</p><pre>@Composable<br>fun ConfirmationScreen(<br>    viewModel: RegistrationViewModel,<br>    onSubmit: () -&gt; Unit<br>) {<br>    val state by viewModel.state.collectAsStateWithLifecycle()<br><br>    Column {<br>        Text(text = &quot;Email: ${state.email}&quot;)<br>        Text(text = &quot;Name: ${state.displayName}&quot;)<br>        Button(onClick = onSubmit) {<br>            Text(&quot;Create account&quot;)<br>        }<br>    }<br>}</pre><p>When the graph is popped, the entry is destroyed, onCleared() runs, and the shared state is gone. The lifetime is bound to the feature, which is exactly what you want.</p><p>If instead you genuinely need the state to be visible across the whole app session, for example a lightweight in-memory user session, you can scope to the Activity by calling hiltViewModel() with the Activity as the owner. Reserve that for state that legitimately lives as long as the Activity, not for transient flows.</p><h3>Where shared ViewModels fit best</h3><p>The multi-step form is the headline case, but the pattern applies anywhere two or more screens operate on the same data within a bounded lifetime.</p><p>Master-detail layouts benefit directly, where a list and a detail pane share a selection ViewModel scoped to the screen that hosts both. Onboarding and wizard flows are a natural fit for the same reason forms are. Tabbed sections under a single bottom navigation entry can share filters or search criteria across tabs. Any coordinated flow, such as a booking process, a checkout, or a document editor with several panels, is a candidate.</p><p>The signal to reach for a shared ViewModel is always the same. Multiple screens read or write the same state, and that state should live only as long as the group of screens does.</p><h3>Conclusion</h3><p>Sharing state across screens does not require serialization gymnastics, callback chains, or leak-prone singletons. It requires understanding that a ViewModel’s sharing behavior is nothing more than which ViewModelStore it resolves from, and that the store you choose sets its lifetime.</p><p>Scope to the Activity when the state must live for the whole session. Scope to a navigation graph, whether through navGraphViewModels() in Fragments or a graph back stack entry in Compose, when the state belongs to a self-contained flow. In both cases you get shared, observable state with automatic cleanup and cancellation, which is exactly the guarantee a hand-written state holder can never give you.</p><p>Get the scope right and the shared ViewModel becomes one of the most reliable tools in the Android toolkit. Multiple screens, one source of truth, and a lifecycle that ends precisely when it should.</p><p>Thanks for reading!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b8dc5c0e3ea9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[MVI in Android — Designing Screens That Can Only Be in One State at a Time]]></title>
            <link>https://medium.com/@aleyvaschz/mvi-in-android-designing-screens-that-can-only-be-in-one-state-at-a-time-1ad894b8ff3e?source=rss-cdc9b9b616bb------2</link>
            <guid isPermaLink="false">https://medium.com/p/1ad894b8ff3e</guid>
            <category><![CDATA[mvi]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[ui]]></category>
            <dc:creator><![CDATA[Adrian Leyva]]></dc:creator>
            <pubDate>Wed, 12 Aug 2026 15:01:03 GMT</pubDate>
            <atom:updated>2026-08-12T15:01:03.433Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Lb4O7xRnAUHwbj9V721cIw.jpeg" /></figure><blockquote>A practical guide to unidirectional data flow with Kotlin, Coroutines, and Jetpack Compose</blockquote><p>There is a specific kind of bug that every Android developer eventually meets. The tester attaches a screenshot showing a loading spinner spinning on top of an error message, with a half populated list behind both of them. You cannot reproduce it. You read the ViewModel three times and the logic looks correct. Two days later you find it: a network call resolved after the user pulled to refresh, a boolean was flipped in the wrong order, and the screen ended up in a combination of values that nobody ever designed.</p><p>That bug is not a coding mistake in the traditional sense. It is a design consequence. When a screen is described by five independent variables, it can be in thirty two different configurations, and the team only ever thought about four of them. The rest exist anyway, waiting for the right race condition.</p><p>Model View Intent, usually shortened to MVI, is an answer to that problem. It is not a new library, and it is not a replacement for everything you already know. It is a discipline applied on top of the architecture you probably already use, and its central promise is simple, at any moment your screen has exactly one state, that state is produced in exactly one place, and it changes only in response to explicit, named events.</p><p>This article walks through what MVI actually means in a modern Android codebase, how to implement it with Kotlin Flows and Jetpack Compose, how to test it, and when it is the wrong tool.</p><h3>The problem MVI is trying to solve</h3><p>Most Android teams write something close to MVVM. A ViewModel exposes a few observable properties, the UI collects them, and user actions call public methods on the ViewModel. It works well, and for a large number of screens it is exactly the right level of ceremony.</p><p>The friction appears as a screen grows. Consider a typical product search ViewModel written in the conventional style:</p><pre>class ProductListViewModel : ViewModel() {<br><br>    private val _isLoading = MutableStateFlow(false)<br>    val isLoading: StateFlow&lt;Boolean&gt; = _isLoading.asStateFlow()<br><br>    private val _products = MutableStateFlow&lt;List&lt;Product&gt;&gt;(emptyList())<br>    val products: StateFlow&lt;List&lt;Product&gt;&gt; = _products.asStateFlow()<br><br>    private val _error = MutableStateFlow&lt;String?&gt;(null)<br>    val error: StateFlow&lt;String?&gt; = _error.asStateFlow()<br><br>    private val _isEmpty = MutableStateFlow(false)<br>    val isEmpty: StateFlow&lt;Boolean&gt; = _isEmpty.asStateFlow()<br>}</pre><p>There are four independent sources of truth here. Nothing in the type system prevents isLoading from being true while error is non null. Nothing forces isEmpty to stay consistent with products. Every new feature adds another flag, and every flag doubles the number of theoretical states. The UI layer ends up compensating with defensive conditionals, and correctness becomes a matter of everyone remembering to update the right fields in the right order.</p><p>MVI removes that entire category of problem by collapsing those four properties into one.</p><h3>The three parts of the contract</h3><p>An MVI screen is defined by a small contract with three pieces. Writing this contract first, before any implementation, is the most valuable habit the pattern teaches.</p><ul><li><strong>State</strong> is an immutable snapshot of everything the screen needs in order to render. If it is not in the state, it cannot appear on screen.</li><li><strong>Intent</strong> is a user action or a lifecycle signal, expressed in the language of the user rather than the language of the implementation. RetryClicked is an intent. SetLoadingTrue is not.</li><li><strong>Effect</strong> is a one time occurrence that is not part of the state at all: navigating to another screen, showing a snackbar, triggering haptic feedback.</li></ul><p>For a product search screen the contract looks like this:</p><pre>data class ProductListState(<br>    val query: String = &quot;&quot;,<br>    val content: Content = Content.Idle,<br>    val isRefreshing: Boolean = false<br>) {<br>    sealed interface Content {<br>        data object Idle : Content<br>        data object Loading : Content<br>        data class Success(val products: List&lt;Product&gt;) : Content<br>        data object Empty : Content<br>        data class Failure(val message: String) : Content<br>    }<br>}<br><br>sealed interface ProductListIntent {<br>    data class QueryChanged(val query: String) : ProductListIntent<br>    data object SearchSubmitted : ProductListIntent<br>    data object RetryClicked : ProductListIntent<br>    data class ProductClicked(val productId: String) : ProductListIntent<br>}<br><br>sealed interface ProductListEffect {<br>    data class NavigateToDetail(val productId: String) : ProductListEffect<br>    data class ShowMessage(val message: String) : ProductListEffect<br>}</pre><p>Notice what the Content hierarchy accomplishes. Loading and failure are no longer independent booleans that happen to coexist. They are mutually exclusive branches of a sealed interface, so the impossible combination that produced our opening bug is now unrepresentable. The compiler enforces the design decision instead of a code review comment.</p><p>The separation between state and effect matters more than it first appears. State is replayed: when the device rotates or the process is restored, the UI re renders from the latest state and that is correct behavior. An effect must not be replayed. Nobody wants the same snackbar to reappear on every configuration change, and nobody wants to navigate twice. Modeling them as separate channels is what keeps that distinction honest.</p><h3>Separating what the user does from what the system observes</h3><p>A refinement that saves a great deal of pain in real projects is distinguishing intents from internal events. An intent comes from outside the ViewModel. An internal event is the result of work the ViewModel started: a repository responded, a timer fired, a cache emitted new data.</p><p>Both need to modify state, but they have different origins and different names. Keeping them separate prevents the intent hierarchy from filling up with entries like DataLoadedSuccessfully, which the user never triggers and which should never be callable from the UI layer.</p><pre>internal sealed interface ProductListEvent {<br>    data class QueryUpdated(val query: String) : ProductListEvent<br>    data object LoadStarted : ProductListEvent<br>    data class LoadSucceeded(val products: List&lt;Product&gt;) : ProductListEvent<br>    data class LoadFailed(val message: String) : ProductListEvent<br>    data class RefreshingChanged(val isRefreshing: Boolean) : ProductListEvent<br>}</pre><h3>The reducer</h3><p>The reducer is where MVI earns its reputation. It is a pure function that takes the current state and an event, and returns the next state. It performs no input or output, launches no coroutines, and touches nothing outside its arguments.</p><pre>internal fun ProductListState.reduce(event: ProductListEvent): ProductListState =<br>    when (event) {<br>        is ProductListEvent.QueryUpdated -&gt; copy(query = event.query)<br><br>        ProductListEvent.LoadStarted -&gt; copy(<br>            content = if (content is ProductListState.Content.Success) {<br>                content<br>            } else {<br>                ProductListState.Content.Loading<br>            }<br>        )<br><br>        is ProductListEvent.LoadSucceeded -&gt; copy(<br>            content = if (event.products.isEmpty()) {<br>                ProductListState.Content.Empty<br>            } else {<br>                ProductListState.Content.Success(event.products)<br>            },<br>            isRefreshing = false<br>        )<br><br>        is ProductListEvent.LoadFailed -&gt; copy(<br>            content = ProductListState.Content.Failure(event.message),<br>            isRefreshing = false<br>        )<br><br>        is ProductListEvent.RefreshingChanged -&gt; copy(isRefreshing = event.isRefreshing)<br>    }</pre><p>Every rule about how this screen behaves now lives in a single readable block. The decision to keep showing existing results while a refresh runs, rather than flashing a spinner, is three lines inside LoadStarted. Previously that rule would have been scattered across a coroutine, a boolean assignment, and a conditional in the layout.</p><p>Because the reducer is pure, it is also trivially testable, and it is the reason MVI screens tend to have unusually high test coverage without anyone forcing the issue.</p><h3>The ViewModel</h3><p>With the contract and the reducer in place, the ViewModel becomes thin. Its job is to receive intents, coordinate asynchronous work, feed events into the reducer, and emit effects.</p><pre>@HiltViewModel<br>class ProductListViewModel @Inject constructor(<br>    private val searchProducts: SearchProductsUseCase<br>) : ViewModel() {<br><br>    private val _state = MutableStateFlow(ProductListState())<br>    val state: StateFlow&lt;ProductListState&gt; = _state.asStateFlow()<br><br>    private val _effects = Channel&lt;ProductListEffect&gt;(Channel.BUFFERED)<br>    val effects: Flow&lt;ProductListEffect&gt; = _effects.receiveAsFlow()<br><br>    private var searchJob: Job? = null<br><br>    fun onIntent(intent: ProductListIntent) {<br>        when (intent) {<br>            is ProductListIntent.QueryChanged -&gt; {<br>                dispatch(ProductListEvent.QueryUpdated(intent.query))<br>            }<br><br>            ProductListIntent.SearchSubmitted -&gt; search(_state.value.query)<br><br>            ProductListIntent.RetryClicked -&gt; search(_state.value.query)<br><br>            is ProductListIntent.ProductClicked -&gt; {<br>                sendEffect(ProductListEffect.NavigateToDetail(intent.productId))<br>            }<br>        }<br>    }<br><br>    private fun search(query: String) {<br>        searchJob?.cancel()<br>        searchJob = viewModelScope.launch {<br>            dispatch(ProductListEvent.LoadStarted)<br>            searchProducts(query)<br>                .onSuccess { products -&gt;<br>                    dispatch(ProductListEvent.LoadSucceeded(products))<br>                }<br>                .onFailure { throwable -&gt;<br>                    dispatch(ProductListEvent.LoadFailed(throwable.toUserMessage()))<br>                    sendEffect(ProductListEffect.ShowMessage(throwable.toUserMessage()))<br>                }<br>        }<br>    }<br><br>    private fun dispatch(event: ProductListEvent) {<br>        _state.update { current -&gt; current.reduce(event) }<br>    }<br><br>    private fun sendEffect(effect: ProductListEffect) {<br>        _effects.trySend(effect)<br>    }<br>}</pre><p>Two details are worth pausing on.</p><p>The first is _state.update { }. Using the atomic update function rather than assigning to _state.value guarantees that concurrent emissions from different coroutines apply on top of each other rather than overwriting one another. In a screen with several parallel data sources, this is the difference between correct and occasionally wrong.</p><p>The second is searchJob?.cancel(). Structured concurrency handles cancellation for you, but only if you hold the reference. Cancelling the previous search before starting a new one is what prevents a slow response for the query &quot;sh&quot; from arriving after the fast response for &quot;shoes&quot; and overwriting it. MVI does not solve out of order results by itself. It gives you a single place to solve them.</p><h3>Connecting the UI</h3><p>The Compose layer receives one state object and sends intents back. It contains no business decisions.</p><pre>@Composable<br>fun ProductListRoute(<br>    onNavigateToDetail: (String) -&gt; Unit,<br>    viewModel: ProductListViewModel = hiltViewModel()<br>) {<br>    val state by viewModel.state.collectAsStateWithLifecycle()<br>    val snackbarHostState = remember { SnackbarHostState() }<br>    val lifecycleOwner = LocalLifecycleOwner.current<br><br>    LaunchedEffect(viewModel, lifecycleOwner) {<br>        viewModel.effects<br>            .flowWithLifecycle(lifecycleOwner.lifecycle, Lifecycle.State.STARTED)<br>            .collect { effect -&gt;<br>                when (effect) {<br>                    is ProductListEffect.NavigateToDetail -&gt; {<br>                        onNavigateToDetail(effect.productId)<br>                    }<br>                    is ProductListEffect.ShowMessage -&gt; {<br>                        snackbarHostState.showSnackbar(effect.message)<br>                    }<br>                }<br>            }<br>    }<br><br>    ProductListScreen(<br>        state = state,<br>        snackbarHostState = snackbarHostState,<br>        onIntent = viewModel::onIntent<br>    )<br>}<br><br>@Composable<br>private fun ProductListScreen(<br>    state: ProductListState,<br>    snackbarHostState: SnackbarHostState,<br>    onIntent: (ProductListIntent) -&gt; Unit<br>) {<br>    Scaffold(<br>        snackbarHost = { SnackbarHost(snackbarHostState) }<br>    ) { padding -&gt;<br>        Column(modifier = Modifier.padding(padding)) {<br>            SearchField(<br>                query = state.query,<br>                onQueryChange = { onIntent(ProductListIntent.QueryChanged(it)) },<br>                onSubmit = { onIntent(ProductListIntent.SearchSubmitted) }<br>            )<br><br>            when (val content = state.content) {<br>                ProductListState.Content.Idle -&gt; IdleHint()<br>                ProductListState.Content.Loading -&gt; FullScreenLoader()<br>                ProductListState.Content.Empty -&gt; EmptyResults(query = state.query)<br>                is ProductListState.Content.Failure -&gt; ErrorMessage(<br>                    message = content.message,<br>                    onRetry = { onIntent(ProductListIntent.RetryClicked) }<br>                )<br>                is ProductListState.Content.Success -&gt; ProductGrid(<br>                    products = content.products,<br>                    onProductClick = { onIntent(ProductListIntent.ProductClicked(it)) }<br>                )<br>            }<br>        }<br>    }<br>}</pre><p>The exhaustive when over the sealed interface is a quiet but significant benefit. Add a new content branch next quarter and the compiler will point at every screen that needs to handle it. There is no equivalent guarantee when the state is a bag of booleans.</p><p>Splitting the route from the stateless screen also means the screen composable takes plain parameters, which makes previews and screenshot tests straightforward.</p><h3>Testing becomes mechanical</h3><p>The reducer is a pure function, so testing behavior requires no coroutine machinery at all.</p><pre>@Test<br>fun `keeps existing results visible while refreshing`() {<br>    val initial = ProductListState(<br>        query = &quot;shoes&quot;,<br>        content = ProductListState.Content.Success(listOf(sampleProduct))<br>    )<br><br>    val result = initial.reduce(ProductListEvent.LoadStarted)<br><br>    assertThat(result.content).isEqualTo(initial.content)<br>}<br><br>@Test<br>fun `empty response maps to empty content`() {<br>    val result = ProductListState(query = &quot;shoes&quot;)<br>        .reduce(ProductListEvent.LoadSucceeded(products = emptyList()))<br><br>    assertThat(result.content).isEqualTo(ProductListState.Content.Empty)<br>}</pre><p>For the ViewModel itself, you assert on the sequence of emitted states, which reads almost like a specification of the feature.</p><pre>@Test<br>fun `failed search emits failure state and a message effect`() = runTest {<br>    coEvery { searchProducts(&quot;shoes&quot;) } returns Result.failure(IOException())<br>    val viewModel = ProductListViewModel(searchProducts)<br><br>    viewModel.state.test {<br>        assertThat(awaitItem().content).isEqualTo(ProductListState.Content.Idle)<br><br>        viewModel.onIntent(ProductListIntent.QueryChanged(&quot;shoes&quot;))<br>        awaitItem()<br><br>        viewModel.onIntent(ProductListIntent.SearchSubmitted)<br>        assertThat(awaitItem().content).isEqualTo(ProductListState.Content.Loading)<br>        assertThat(awaitItem().content).isInstanceOf(ProductListState.Content.Failure::class.java)<br>    }<br>}</pre><h3>Important considerations</h3><p>MVI has real costs, and teams that adopt it without discussing them tend to abandon it halfway.</p><ul><li><strong>The state class becomes a landfill.</strong> On a complex screen it is tempting to add one more nullable field for every edge case. Push back on this. If a piece of data belongs to a self contained section of the screen, model it as a nested sealed type or as its own sub state, and reduce it independently.</li><li><strong>Recomposition costs rise if you are careless.</strong> A single large state object means any change emits a new instance. Compose handles this well when the state is stable and composables read only what they need, but passing the entire state object down five levels defeats that. Pass the narrowest slice each composable actually requires.</li><li><strong>Effects can be lost.</strong> A Channel delivers to a single collector. If your effect flow is collected in a composable that leaves composition at the wrong moment, an event can disappear. Using a buffered channel with lifecycle aware collection, as shown above, covers the common cases. Anything genuinely critical, such as a completed payment, belongs in state or in persistent storage rather than in a transient effect.</li><li><strong>Boilerplate is real.</strong> Three types plus a reducer for a screen that shows a static list of settings is not a good trade. A shared generic base class or a small internal library reduces the repetition, but it does not eliminate the conceptual overhead.</li><li><strong>It is not required everywhere.</strong> A splash screen, a static about page, or a simple form with two fields does not benefit. MVI pays off in proportion to how many asynchronous sources a screen coordinates and how many visual states it can occupy. Use it on the checkout flow and the search results. Skip it on the terms and conditions.</li></ul><h3>Conclusion</h3><p>MVI is less a framework than a set of constraints you accept voluntarily. You give up the convenience of mutating a few independent fields, and in exchange you get a screen whose behavior is described by one immutable type and one pure function. Reproducing a bug becomes a matter of constructing a state object, and adding a feature becomes adding a branch the compiler will not let you forget to handle. Start with the screen that already worries you. Write the contract before the implementation, keep the reducer pure, and let the sealed types eliminate the combinations that were never supposed to exist.</p><p>Thanks for reading!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1ad894b8ff3e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Dependency Injection in Android — A Practical Guide to Hilt]]></title>
            <link>https://medium.com/@aleyvaschz/dependency-injection-in-android-a-practical-guide-to-hilt-a7930830a2a8?source=rss-cdc9b9b616bb------2</link>
            <guid isPermaLink="false">https://medium.com/p/a7930830a2a8</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[android-hilt]]></category>
            <category><![CDATA[clean-architecture]]></category>
            <category><![CDATA[dependency-injection]]></category>
            <dc:creator><![CDATA[Adrian Leyva]]></dc:creator>
            <pubDate>Mon, 10 Aug 2026 15:01:03 GMT</pubDate>
            <atom:updated>2026-08-10T15:01:03.161Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yC8zbKn3xmPIVf6CHSj25Q.png" /></figure><blockquote>How to remove boilerplate, decouple your classes, and build testable Android apps</blockquote><p>Every Android developer eventually hits the same wall. A ViewModel needs a Repository. The Repository needs an API service and a local database. The API service needs a configured Retrofit instance, which needs an OkHttpClient, which needs a logging interceptor and an auth token provider. Multiply that by every screen in your app, and you end up with a web of manually constructed objects that is fragile, repetitive, and painful to test.</p><p>This is the exact problem Dependency Injection was designed to solve, and it is why frameworks like Hilt exist. In this article, we will walk through what Dependency Injection actually means, why manual DI does not scale, and how Hilt lets you wire your entire Android app with a handful of annotations instead of hundreds of lines of factory code. By the end, you will have a clear mental model of Hilt and a working example you can adapt to your own projects.</p><h3>What Dependency Injection Actually Means</h3><p>Dependency Injection, or DI, is a design pattern where a class receives the objects it depends on from an external source instead of creating them itself. Those external objects are its dependencies, and the class it depends on them for is, unsurprisingly, the dependent.</p><p>Consider a simple example without DI:</p><pre>class UserRepository {<br>    private val apiService = ApiService()<br>    private val database = AppDatabase()<br><br>    fun getUser(id: String) = apiService.fetchUser(id)<br>}</pre><p>UserRepository is responsible for two things it should not care about: how to build an ApiService and how to build an AppDatabase. If either constructor changes, or if you want to swap the real ApiService for a fake one during testing, you have to modify UserRepository itself. The class is tightly coupled to its dependencies.</p><p>Now compare that to the same class using constructor injection:</p><pre>class UserRepository(<br>    private val apiService: ApiService,<br>    private val database: AppDatabase<br>) {<br>    fun getUser(id: String) = apiService.fetchUser(id)<br>}</pre><p>UserRepository no longer knows how to build an ApiService or an AppDatabase. It simply declares that it needs them, and something else is responsible for providing them. This single change makes the class easier to read, easier to reuse, and trivial to test, since you can pass in mocked or fake implementations during unit tests.</p><h3>The Problem With Manual Dependency Injection</h3><p>Constructor injection is a great pattern in isolation, but someone still has to build the full object graph. In a small app, you might do this by hand in a single place, often called a ServiceLocator or a manually written AppContainer:</p><pre>class AppContainer {<br>    private val okHttpClient = OkHttpClient.Builder()<br>        .addInterceptor(AuthInterceptor())<br>        .build()<br><br>    private val retrofit = Retrofit.Builder()<br>        .baseUrl(&quot;https://api.example.com&quot;)<br>        .client(okHttpClient)<br>        .addConverterFactory(GsonConverterFactory.create())<br>        .build()<br><br>    val apiService: ApiService = retrofit.create(ApiService::class.java)<br>    val database: AppDatabase = Room.databaseBuilder(<br>        context, AppDatabase::class.java, &quot;app.db&quot;<br>    ).build()<br><br>    val userRepository = UserRepository(apiService, database)<br>}</pre><p>This works for a while, but it does not scale correctly. As your app grows, you have to manage object lifetimes yourself, decide which instances should be singletons versus scoped to a single screen, and manually thread dependencies through every Activity, Fragment, and ViewModel that needs them. On larger codebases, this container becomes a bottleneck that every feature team has to touch, and subtle bugs creep in around object lifecycles and memory leaks.</p><p>This is exactly the gap Hilt is built to close.</p><h3>Why Hilt</h3><p>Hilt is Google’s recommended Dependency Injection library for Android. It is built on top of Dagger, which handles the underlying compile-time dependency graph, but it removes most of Dagger’s boilerplate by defining standard components that map directly to Android’s own lifecycle: Application, Activity, Fragment, ViewModel, and more.</p><p>Because the dependency graph is generated at compile time rather than resolved through reflection at runtime, Hilt catches missing or misconfigured dependencies as build errors instead of runtime crashes. It also integrates natively with Jetpack libraries, including ViewModel, WorkManager, and Navigation, which means far less custom wiring than plain Dagger requires.</p><h4>Setting Up Hilt</h4><p>Start by adding the Hilt Gradle plugin and dependencies to your project.</p><p>In your project level build.gradle.kts:</p><pre>plugins {<br>    id(&quot;com.google.dagger.hilt.android&quot;) version &quot;2.51.1&quot; apply false<br>}</pre><p>In your module level build.gradle.kts:</p><pre>plugins {<br>    id(&quot;com.google.dagger.hilt.android&quot;)<br>    kotlin(&quot;kapt&quot;)<br>}<br><br>dependencies {<br>    implementation(&quot;com.google.dagger:hilt-android:2.51.1&quot;)<br>    kapt(&quot;com.google.dagger:hilt-android-compiler:2.51.1&quot;)<br>    implementation(&quot;androidx.hilt:hilt-navigation-compose:1.2.0&quot;)<br>}</pre><p>Next, annotate your Application class with @HiltAndroidApp. This triggers Hilt&#39;s code generation and creates the top level dependency container that the rest of the app hangs off of.</p><pre>@HiltAndroidApp<br>class MyApplication : Application()</pre><p>Do not forget to register this class in your AndroidManifest.xml:</p><pre>&lt;application<br>    android:name=&quot;.MyApplication&quot;<br>    ...&gt;<br>&lt;/application&gt;</pre><h4>Providing Dependencies With Modules</h4><p>Hilt needs to know how to build the objects you request. For classes you own, like UserRepository, you can usually annotate the constructor directly with @Inject, and Hilt figures out how to build it automatically as long as it also knows how to build its dependencies.</p><pre>class UserRepository @Inject constructor(<br>    private val apiService: ApiService,<br>    private val database: AppDatabase<br>) {<br>    suspend fun getUser(id: String) = apiService.fetchUser(id)<br>}</pre><p>For classes you do not own, such as Retrofit, OkHttpClient, or a Room database, you need to tell Hilt explicitly how to construct them. This is done through a Hilt module, which is an abstract class or object annotated with @Module and @InstallIn, the latter specifying which Hilt component the bindings belong to.</p><pre>@Module<br>@InstallIn(SingletonComponent::class)<br>object NetworkModule {<br><br>    @Provides<br>    @Singleton<br>    fun provideOkHttpClient(): OkHttpClient {<br>        return OkHttpClient.Builder()<br>            .addInterceptor(AuthInterceptor())<br>            .build()<br>    }<br><br>    @Provides<br>    @Singleton<br>    fun provideRetrofit(okHttpClient: OkHttpClient): Retrofit {<br>        return Retrofit.Builder()<br>            .baseUrl(&quot;https://api.example.com&quot;)<br>            .client(okHttpClient)<br>            .addConverterFactory(GsonConverterFactory.create())<br>            .build()<br>    }<br><br>    @Provides<br>    @Singleton<br>    fun provideApiService(retrofit: Retrofit): ApiService {<br>        return retrofit.create(ApiService::class.java)<br>    }<br>}</pre><p>@InstallIn(SingleComponent::class) tells Hilt that these bindings live in the application level container, so they are created once and reused for the entire lifetime of the app. Hilt exposes several components tied to Android lifecycle owners, including ActivityComponent, FragmentComponent, and ViewModelComponent, each with a matching scope annotation such as @ActivityScoped or @ViewModelScoped.</p><p>For the local database, a similar module works well:</p><pre>@Module<br>@InstallIn(SingletonComponent::class)<br>object DatabaseModule {<br><br>    @Provides<br>    @Singleton<br>    fun provideDatabase(@ApplicationContext context: Context): AppDatabase {<br>        return Room.databaseBuilder(<br>            context,<br>            AppDatabase::class.java,<br>            &quot;app.db&quot;<br>        ).build()<br>    }<br>}</pre><p>Notice the @ApplicationContext qualifier. Hilt provides the application Context out of the box, which avoids the common mistake of leaking an Activity context into a long lived singleton.</p><h4>Injecting Into Android Classes</h4><p>Once your bindings are in place, injecting dependencies into an Activity, Fragment, or ViewModel requires very little code. Annotate the class with @AndroidEntryPoint, and Hilt handles the rest.</p><pre>@AndroidEntryPoint<br>class UserProfileActivity : AppCompatActivity() {<br><br>    @Inject<br>    lateinit var userRepository: UserRepository<br><br>    override fun onCreate(savedInstanceState: Bundle?) {<br>        super.onCreate(savedInstanceState)<br>        // userRepository is already initialized here<br>    }<br>}</pre><p>ViewModels get their own annotation, @HiltViewModel, which works together with @AndroidEntryPoint on the hosting Activity or Fragment and with the hiltViewModel() composable function when you are working in Jetpack Compose.</p><pre>@HiltViewModel<br>class UserProfileViewModel @Inject constructor(<br>    private val userRepository: UserRepository<br>) : ViewModel() {<br><br>    private val _uiState = MutableStateFlow&lt;UserUiState&gt;(UserUiState.Loading)<br>    val uiState: StateFlow&lt;UserUiState&gt; = _uiState.asStateFlow()<br><br>    fun loadUser(id: String) {<br>        viewModelScope.launch {<br>            _uiState.value = try {<br>                UserUiState.Success(userRepository.getUser(id))<br>            } catch (e: IOException) {<br>                UserUiState.Error(e.message)<br>            }<br>        }<br>    }<br>}</pre><p>In a Compose screen, retrieving this ViewModel is a single line, with no manual factory required:</p><pre>@Composable<br>fun UserProfileScreen(<br>    viewModel: UserProfileViewModel = hiltViewModel()<br>) {<br>    val uiState by viewModel.uiState.collectAsStateWithLifecycle()<br>    // render uiState<br>}</pre><p>Compare this to the manual container from earlier. There is no AppContainer to thread through every screen, no factory classes to hand write, and no risk of forgetting to pass a dependency down through three layers of constructors. Hilt generates all of that wiring for you at compile time.</p><h4>Binding Interfaces to Implementations</h4><p>A common pattern is depending on an interface rather than a concrete class, which keeps your code decoupled and makes swapping implementations for testing straightforward. Hilt supports this through @Binds, used inside an abstract module.</p><pre>interface UserRepository {<br>    suspend fun getUser(id: String): User<br>}<br><br>class UserRepositoryImpl @Inject constructor(<br>    private val apiService: ApiService<br>) : UserRepository {<br>    override suspend fun getUser(id: String) = apiService.fetchUser(id)<br>}<br><br>@Module<br>@InstallIn(SingletonComponent::class)<br>abstract class RepositoryModule {<br><br>    @Binds<br>    abstract fun bindUserRepository(<br>        impl: UserRepositoryImpl<br>    ): UserRepository<br>}</pre><p>Anywhere you now inject UserRepository, Hilt automatically supplies UserRepositoryImpl. In tests, you can create a separate test module that binds a fake implementation instead, without touching any production code.</p><h4>Why This Matters for Testing</h4><p>This is where Dependency Injection pays for itself. Because your classes depend on abstractions supplied from the outside, you can substitute real implementations with fakes or mocks in unit tests without any framework involvement at all.</p><pre>class FakeUserRepository : UserRepository {<br>    override suspend fun getUser(id: String) = User(id, &quot;Test User&quot;)<br>}<br><br>class UserProfileViewModelTest {<br><br>    @Test<br>    fun `loadUser updates state to Success`() = runTest {<br>        val viewModel = UserProfileViewModel(FakeUserRepository())<br><br>        viewModel.loadUser(&quot;123&quot;)<br><br>        assertTrue(viewModel.uiState.value is UserUiState.Success)<br>    }<br>}</pre><p>No Hilt annotations are needed in this test at all, because UserProfileViewModel only depends on the UserRepository interface. For instrumented tests where you do want Hilt to manage the graph, the library ships hilt-android-testing, which provides @HiltAndroidTest and a custom test runner so you can swap in test modules while still exercising the real Android lifecycle.</p><h3>Common Mistakes</h3><p>A few mistakes come up repeatedly when teams adopt Hilt:</p><ul><li>Injecting an Activity context into a class scoped to SingletonComponent causes memory leaks, since the singleton will outlive the Activity. Always use @ApplicationContext for anything living at the application scope.</li><li>Forgetting @InstallIn on a module produces a compile error, but forgetting the correct component, such as installing an Activity scoped binding into SingletonComponent, produces a working build with the wrong lifetime, which is harder to catch.</li><li>Overusing @Singleton for objects that do not need to survive the whole app lifecycle wastes memory and can cause stale data to persist longer than expected. Reach for @ActivityScoped or @ViewModelScoped when the object&#39;s lifetime should match a narrower scope.</li></ul><h3>Conclusion</h3><p>Dependency Injection is not about adding a library to your project. It is a discipline, classes declare what they need instead of constructing it themselves, which makes your codebase more modular, easier to reason about, and far easier to test. Hilt takes that discipline and removes almost all of the ceremony required to apply it consistently across an Android app, from a single Activity up to a codebase with hundreds of screens.</p><p>Once your modules and entry points are set up, adding a new dependency becomes as simple as adding a parameter to a constructor. That small shift, repeated across every class in your app, is what separates a codebase that scales cleanly from one that collapses under its own wiring. If you are still manually constructing your Repositories and ViewModels, migrating to Hilt is one of the highest leverage changes you can make to your Android architecture.</p><p>Thanks for reading!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a7930830a2a8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Beyond the Stack Trace — A Practical Guide to Debugging Android Apps]]></title>
            <link>https://medium.com/@aleyvaschz/beyond-the-stack-trace-a-practical-guide-to-debugging-android-apps-bd1796975e43?source=rss-cdc9b9b616bb------2</link>
            <guid isPermaLink="false">https://medium.com/p/bd1796975e43</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[tools]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[debugging]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[Adrian Leyva]]></dc:creator>
            <pubDate>Wed, 05 Aug 2026 15:01:04 GMT</pubDate>
            <atom:updated>2026-08-05T15:01:04.516Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uBDNTvk3H1ufgNqtm2-pbw.jpeg" /></figure><blockquote>A developer’s toolkit for tracking down what went wrong</blockquote><h3>How to move from guessing to knowing when your app misbehaves</h3><p>Every Android developer knows the feeling. The app crashes on a device you do not own, a screen renders correctly on the emulator but breaks in production, or a network call that worked yesterday silently fails today. The instinct is often to add a Log.d call, rebuild, and hope the new log line lands near the problem. That approach works occasionally, but it does not scale, and it rarely gets you to the root cause quickly.</p><p>Debugging is a skill separate from writing code, and it deserves the same deliberate practice. This article walks through the tools and techniques that turn debugging from a guessing game into a repeatable process, covering Logcat, breakpoints, the Layout Inspector, Compose-specific tooling, coroutine debugging, network inspection, memory leak detection, and strategies for issues that only appear in production. The goal is not to memorize every tool, but to build a mental checklist you can reach for depending on the symptom in front of you.</p><h3>Start with Logcat, but use it deliberately</h3><p>Logcat is the most familiar tool in the Android toolbox, and also the most misused. Scattering Log.d calls throughout a codebase creates noise that is hard to filter later. A more disciplined approach uses tags consistently and log levels that reflect actual severity.</p><pre>private const val TAG = &quot;PaymentRepository&quot;<br><br>class PaymentRepository(private val api: PaymentApi) {<br><br>    suspend fun processPayment(request: PaymentRequest): Result&lt;PaymentResponse&gt; {<br>        Log.d(TAG, &quot;Processing payment for order ${request.orderId}&quot;)<br>        return try {<br>            val response = api.submitPayment(request)<br>            Log.i(TAG, &quot;Payment succeeded for order ${request.orderId}&quot;)<br>            Result.success(response)<br>        } catch (e: HttpException) {<br>            Log.e(TAG, &quot;Payment failed with HTTP ${e.code()} for order ${request.orderId}&quot;, e)<br>            Result.failure(e)<br>        }<br>    }<br>}</pre><p>Two habits make Logcat far more useful. First, always include identifying context in the message, such as an order ID or user ID, so you can trace a single flow through a noisy log stream. Second, use Android Studio’s Logcat filters, which support regular expressions and package-level scoping, instead of scrolling through unfiltered output. A filter like tag:PaymentRepository package:mine level:ERROR isolates exactly what matters and saves significant time during an active investigation.</p><h3>Breakpoints do more than pause execution</h3><p>Most developers use breakpoints as simple pause points, but Android Studio supports several breakpoint types that are underused. Conditional breakpoints only trigger when an expression evaluates to true, which is essential when a bug occurs on the fiftieth iteration of a loop rather than the first.</p><pre>fun calculateDiscount(items: List&lt;CartItem&gt;): Double {<br>    var total = 0.0<br>    for (item in items) {<br>        // Right-click this line in Android Studio and set a condition,<br>        // for example: item.price &lt; 0<br>        total += item.price * item.quantity<br>    }<br>    return total<br>}</pre><p>Setting the condition item.price &lt; 0 on that line means execution only stops when a genuinely invalid item appears, instead of forcing you to step through every item manually. Logpoints are equally valuable: they let you print a message to Logcat without modifying source code and without the overhead of a full pause, which is ideal for production-adjacent debug builds where you want visibility without behavioral change.</p><p>Exception breakpoints deserve special mention. Configuring Android Studio to break on any thrown NullPointerException or a custom exception type catches the exact moment something goes wrong, rather than the moment a generic crash handler reports it several stack frames later.</p><h3>Inspecting layout and Compose state</h3><p>For UI issues, the Layout Inspector remains the fastest way to understand what is actually being rendered, including view hierarchies, padding, constraints, and resolved attribute values at runtime. It is particularly useful when a layout looks correct in the preview but wrong on a physical device, since it captures the live render tree rather than a static approximation.</p><p>Jetpack Compose introduces a different debugging surface: recomposition. Composables can recompose more often than necessary, which quietly degrades performance without producing any error. The Layout Inspector’s Compose mode shows recomposition counts per composable, but you can also instrument this directly during development.</p><pre>@Composable<br>fun ProductCard(product: Product) {<br>    SideEffect {<br>        Log.d(&quot;Recomposition&quot;, &quot;ProductCard recomposed for ${product.id}&quot;)<br>    }<br><br>    Card(modifier = Modifier.padding(8.dp)) {<br>        Text(text = product.name, style = MaterialTheme.typography.titleMedium)<br>        Text(text = &quot;$${product.price}&quot;, style = MaterialTheme.typography.bodyMedium)<br>    }<br>}</pre><p>If this log line fires far more often than expected, the usual culprits are unstable parameters, such as a lambda recreated on every parent recomposition, or a mutable list passed directly instead of an immutable, stable collection. Wrapping unstable types with @Stable or @Immutable annotations, or hoisting state correctly, typically resolves the issue.</p><h3>Debugging coroutines and Flow</h3><p>Asynchronous code introduces failure modes that do not show up as a traditional crash: a coroutine that never completes, a Flow that stops emitting, or a race condition that only appears under load. The CoroutineExceptionHandler is the first line of defense, since unhandled exceptions in coroutines can otherwise disappear silently or crash the app far from their origin.</p><pre>class OrderViewModel(private val repository: OrderRepository) : ViewModel() {<br><br>    private val exceptionHandler = CoroutineExceptionHandler { _, exception -&gt;<br>        Log.e(&quot;OrderViewModel&quot;, &quot;Unhandled coroutine exception&quot;, exception)<br>    }<br><br>    fun loadOrders() {<br>        viewModelScope.launch(exceptionHandler) {<br>            repository.getOrders()<br>                .onStart { Log.d(&quot;OrderViewModel&quot;, &quot;Fetching orders started&quot;) }<br>                .catch { e -&gt; Log.e(&quot;OrderViewModel&quot;, &quot;Flow collection failed&quot;, e) }<br>                .collect { orders -&gt; Log.d(&quot;OrderViewModel&quot;, &quot;Received ${orders.size} orders&quot;) }<br>        }<br>    }<br>}</pre><p>The onStart and onEach operators are useful diagnostic tools in their own right, since they let you observe a Flow&#39;s lifecycle without altering its logic. For structured concurrency issues, such as a child coroutine outliving its expected scope, Android Studio&#39;s Coroutine Debugger panel shows every active coroutine, its state, and its stack, which is far more reliable than trying to infer this from log timestamps alone.</p><h3>Inspecting network traffic</h3><p>Backend integration bugs are common, and Android Studio’s built-in Network Inspector or a library like Chucker can show request and response bodies, headers, and timing directly on the device. Chucker is particularly convenient because it works entirely in-app and requires no separate proxy setup.</p><pre>val client = OkHttpClient.Builder()<br>    .addInterceptor(ChuckerInterceptor.Builder(context).build())<br>    .addInterceptor(HttpLoggingInterceptor().apply {<br>        level = HttpLoggingInterceptor.Level.BODY<br>    })<br>    .build()</pre><p>With this configuration in place, a tap on the Chucker notification opens a full history of network calls, which makes it straightforward to confirm whether a bug originates on the client or the server. This is especially valuable when a backend team reports that everything looks correct on their end, since you can show the exact payload the app actually sent.</p><h3>Catching memory leaks before users do</h3><p>Memory leaks in Android are usually caused by a long-lived object, such as a singleton or a static reference, holding onto a short-lived one, such as an Activity or Fragment. These leaks do not crash the app immediately, but they degrade performance over time and eventually trigger an OutOfMemoryError. LeakCanary remains the standard tool for catching these automatically during development.</p><pre>// build.gradle.kts (app module)<br>dependencies {<br>    debugImplementation(&quot;com.squareup.leakcanary:leakcanary-android:2.14&quot;)<br>}</pre><p>No additional code is required beyond this dependency. LeakCanary automatically detects retained objects after Activities and Fragments are destroyed, and it produces a readable leak trace pointing to the exact reference chain responsible. Reading that trace is a skill in itself: focus on the last few frames closest to the leaked object, since that is usually where the fix belongs, whether it is unregistering a listener, cancelling a coroutine scope, or nulling out a view binding in onDestroyView.</p><h3>When bugs only happen in production</h3><p>Some of the hardest bugs never reproduce locally. This is where structured crash reporting earns its place. Firebase Crashlytics is the most common choice, and its value increases significantly when you attach custom keys and breadcrumbs before a crash occurs, rather than relying on the stack trace alone.</p><pre>class CheckoutActivity : AppCompatActivity() {<br><br>    override fun onCreate(savedInstanceState: Bundle?) {<br>        super.onCreate(savedInstanceState)<br>        FirebaseCrashlytics.getInstance().apply {<br>            setCustomKey(&quot;cart_item_count&quot;, cartViewModel.itemCount)<br>            setCustomKey(&quot;payment_method&quot;, cartViewModel.selectedPaymentMethod)<br>            log(&quot;CheckoutActivity created&quot;)<br>        }<br>    }<br>}</pre><p>When a crash does occur, these custom keys appear alongside the stack trace in the Crashlytics dashboard, turning an anonymous crash report into one with enough context to reproduce the failure locally. It is worth treating breadcrumbs as part of normal development practice for critical flows, such as checkout or authentication, rather than adding them reactively after an incident.</p><p>For ANRs specifically, the StrictMode API is worth enabling in debug builds, since it flags disk or network operations running on the main thread before they become a user-facing freeze.</p><pre>class DebugApplication : Application() {<br>    override fun onCreate() {<br>        super.onCreate()<br>        StrictMode.setThreadPolicy(<br>            StrictMode.ThreadPolicy.Builder()<br>                .detectDiskReads()<br>                .detectDiskWrites()<br>                .detectNetwork()<br>                .penaltyLog()<br>                .build()<br>        )<br>    }<br>}</pre><h3>Conclusion</h3><p>Debugging Android applications is not about having the right tool open at the right time, though that certainly helps. It is about narrowing the space between symptom and cause as efficiently as possible, using the right instrument for the type of problem in front of you. Logcat and breakpoints handle the everyday cases, the Layout Inspector and Compose tooling handle rendering and recomposition issues, coroutine and Flow debugging handle asynchronous logic, and Crashlytics together with StrictMode extend visibility into production where local reproduction is not possible. None of these tools replace careful reasoning about the code, but together they remove the guesswork, and that is what separates a frustrating debugging session from a short one.</p><p>Thanks for reading!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bd1796975e43" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Beyond the Acronym — SOLID Principles for Android Developers]]></title>
            <link>https://medium.com/@aleyvaschz/beyond-the-acronym-solid-principles-for-android-developers-aa8fd05183a9?source=rss-cdc9b9b616bb------2</link>
            <guid isPermaLink="false">https://medium.com/p/aa8fd05183a9</guid>
            <category><![CDATA[solid-principles]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[clean-code]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[software-architecture]]></category>
            <dc:creator><![CDATA[Adrian Leyva]]></dc:creator>
            <pubDate>Mon, 03 Aug 2026 15:01:02 GMT</pubDate>
            <atom:updated>2026-08-03T15:01:02.451Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*s6VgkxRHFyUEwYRpclNjDg.png" /></figure><blockquote>A practical look at five design principles through real Android examples</blockquote><p>Most Android engineers can picture the file without needing to see it. One class quietly handling networking, database access, UI state, and analytics all at once, grown large enough that nobody wants to be the one who touches it next. Adding a single feature means reading carefully through logic that has no clear boundaries, hoping the change does not ripple into a screen three taps away. This is not an edge case. It’s what happens, reliably, when a codebase grows without best practices.</p><p>SOLID refers to five object-oriented design principles introduced by Robert C. Martin: Single Responsibility, Open/Closed, Liskov Substitution, Interface Segregation, and Dependency Inversion. They were written well before ViewModels or Jetpack Compose existed, but Android development, with its layered architecture and its habit of changing requirements mid-sprint, turns out to be one of the clearest places to see them in action. This article works through each principle using practical Kotlin examples grounded in patterns from real production code, with the goal of showing not only what each principle states, but why it matters once your app has to keep working through months of change you did not plan for.</p><h3>Single Responsibility Principle</h3><p>A class should have one, and only one, reason to change. This does not mean a class should do only one thing in the narrowest sense; it means a class should be answerable to only one actor or concern.</p><p>Consider a common anti-pattern: a ViewModel that fetches user data, formats it for display, and also handles analytics logging.</p><pre>class UserProfileViewModel(<br>    private val api: UserApi,<br>    private val analytics: AnalyticsService<br>) : ViewModel() {<br><br>    private val _uiState = MutableStateFlow&lt;UserUiState&gt;(UserUiState.Loading)<br>    val uiState: StateFlow&lt;UserUiState&gt; = _uiState<br><br>    fun loadUser(userId: String) {<br>        viewModelScope.launch {<br>            try {<br>                val response = api.getUser(userId)<br>                val formattedName = &quot;${response.firstName} ${response.lastName}&quot;.trim()<br>                val formattedJoinDate = SimpleDateFormat(&quot;MMM yyyy&quot;, Locale.US)<br>                    .format(response.joinDate)<br><br>                _uiState.value = UserUiState.Success(<br>                    name = formattedName,<br>                    joinDate = formattedJoinDate<br>                )<br>                analytics.logEvent(&quot;user_profile_loaded&quot;, mapOf(&quot;user_id&quot; to userId))<br>            } catch (e: Exception) {<br>                _uiState.value = UserUiState.Error(e.message ?: &quot;Unknown error&quot;)<br>                analytics.logEvent(&quot;user_profile_error&quot;, mapOf(&quot;user_id&quot; to userId))<br>            }<br>        }<br>    }<br>}</pre><p>This ViewModel changes if the API contract changes, if the date format changes, if the analytics schema changes, or if the display logic changes. Four reasons to change means four sources of risk every time you touch this file. Splitting responsibilities across a mapper, a dedicated analytics tracker, and a leaner ViewModel isolates each concern.</p><pre>class UserDisplayMapper {<br>    fun toDisplayModel(response: UserResponse): UserDisplayModel {<br>        return UserDisplayModel(<br>            name = &quot;${response.firstName} ${response.lastName}&quot;.trim(),<br>            joinDate = SimpleDateFormat(&quot;MMM yyyy&quot;, Locale.US).format(response.joinDate)<br>        )<br>    }<br>}<br><br>class UserProfileAnalyticsTracker(private val analytics: AnalyticsService) {<br>    fun trackLoaded(userId: String) =<br>        analytics.logEvent(&quot;user_profile_loaded&quot;, mapOf(&quot;user_id&quot; to userId))<br><br>    fun trackError(userId: String) =<br>        analytics.logEvent(&quot;user_profile_error&quot;, mapOf(&quot;user_id&quot; to userId))<br>}<br><br>class UserProfileViewModel(<br>    private val api: UserApi,<br>    private val mapper: UserDisplayMapper,<br>    private val tracker: UserProfileAnalyticsTracker<br>) : ViewModel() {<br><br>    private val _uiState = MutableStateFlow&lt;UserUiState&gt;(UserUiState.Loading)<br>    val uiState: StateFlow&lt;UserUiState&gt; = _uiState<br><br>    fun loadUser(userId: String) {<br>        viewModelScope.launch {<br>            try {<br>                val response = api.getUser(userId)<br>                _uiState.value = UserUiState.Success(mapper.toDisplayModel(response))<br>                tracker.trackLoaded(userId)<br>            } catch (e: Exception) {<br>                _uiState.value = UserUiState.Error(e.message ?: &quot;Unknown error&quot;)<br>                tracker.trackError(userId)<br>            }<br>        }<br>    }<br>}</pre><p>Now each class is testable in isolation, and a change to date formatting no longer risks breaking analytics tracking.</p><h3>Open/Closed Principle</h3><p>Software entities should be open for extension but closed for modification. In practice, this means you should be able to add new behavior without rewriting existing, already-tested code.</p><p>A frequent violation shows up in payment processing or notification handling, where a single function grows a new conditional branch every time a new type is introduced.</p><pre>class PaymentProcessor {<br>    fun process(payment: Payment) {<br>        when (payment.type) {<br>            PaymentType.CREDIT_CARD -&gt; processCreditCard(payment)<br>            PaymentType.PAYPAL -&gt; processPayPal(payment)<br>            PaymentType.GOOGLE_PAY -&gt; processGooglePay(payment)<br>            // Every new payment method means editing this function again<br>        }<br>    }<br><br>    private fun processCreditCard(payment: Payment) { /* ... */ }<br>    private fun processPayPal(payment: Payment) { /* ... */ }<br>    private fun processGooglePay(payment: Payment) { /* ... */ }<br>}</pre><p>Every new payment provider requires modifying and redeploying this class, along with re-running regression tests on branches you did not touch. An interface-based approach lets you extend behavior by adding new classes instead.</p><pre>interface PaymentStrategy {<br>    suspend fun process(amount: BigDecimal): PaymentResult<br>}<br><br>class CreditCardPayment(private val gateway: CardGateway) : PaymentStrategy {<br>    override suspend fun process(amount: BigDecimal): PaymentResult =<br>        gateway.charge(amount)<br>}<br><br>class PayPalPayment(private val client: PayPalClient) : PaymentStrategy {<br>    override suspend fun process(amount: BigDecimal): PaymentResult =<br>        client.createOrder(amount)<br>}<br><br>class GooglePayPayment(private val client: GooglePayClient) : PaymentStrategy {<br>    override suspend fun process(amount: BigDecimal): PaymentResult =<br>        client.charge(amount)<br>}<br><br>class PaymentProcessor(private val strategy: PaymentStrategy) {<br>    suspend fun process(amount: BigDecimal): PaymentResult = strategy.process(amount)<br>}</pre><p>Adding Apple Pay or a new regional wallet now means writing a new class that implements PaymentStrategy, with zero changes to PaymentProcessor and no risk of breaking existing payment flows.</p><h3>Liskov Substitution Principle</h3><p>Subtypes must be substitutable for their base types without altering the correctness of the program. If code works with a base class or interface, it should keep working when you swap in any subclass, without surprises.</p><p>A classic violation happens with lists or repositories that are supposed to be interchangeable but are not.</p><pre>interface Repository&lt;T&gt; {<br>    fun getAll(): List&lt;T&gt;<br>    fun add(item: T)<br>}<br><br>class InMemoryRepository&lt;T&gt; : Repository&lt;T&gt; {<br>    private val items = mutableListOf&lt;T&gt;()<br>    override fun getAll(): List&lt;T&gt; = items<br>    override fun add(item: T) { items.add(item) }<br>}<br><br>class ReadOnlyRepository&lt;T&gt;(private val source: List&lt;T&gt;) : Repository&lt;T&gt; {<br>    override fun getAll(): List&lt;T&gt; = source<br>    override fun add(item: T) {<br>        throw UnsupportedOperationException(&quot;This repository is read-only&quot;)<br>    }<br>}</pre><p>Any code written against Repository&lt;T&gt; that calls add will compile fine against ReadOnlyRepository, but will crash at runtime. This silently breaks the contract the interface implies. The fix is to model the capability honestly, either by separating read and write contracts or by making the limitation explicit at the type level.</p><pre>interface ReadableRepository&lt;T&gt; {<br>    fun getAll(): List&lt;T&gt;<br>}<br><br>interface WritableRepository&lt;T&gt; : ReadableRepository&lt;T&gt; {<br>    fun add(item: T)<br>}<br><br>class InMemoryRepository&lt;T&gt; : WritableRepository&lt;T&gt; {<br>    private val items = mutableListOf&lt;T&gt;()<br>    override fun getAll(): List&lt;T&gt; = items<br>    override fun add(item: T) { items.add(item) }<br>}<br><br>class ReadOnlyRepository&lt;T&gt;(private val source: List&lt;T&gt;) : ReadableRepository&lt;T&gt; {<br>    override fun getAll(): List&lt;T&gt; = source<br>}</pre><p>Now a function accepting ReadableRepository&lt;T&gt; can never be handed an object that fails on add, because that method does not exist on the interface it depends on. The compiler enforces the contract instead of the runtime punishing you for it.</p><h3>Interface Segregation Principle</h3><p>Clients should not be forced to depend on methods they do not use. Large, catch-all interfaces tend to accumulate unrelated responsibilities, forcing every implementation to stub out methods it has no real use for.</p><pre>interface UserActions {<br>    fun login(credentials: Credentials)<br>    fun logout()<br>    fun updateProfile(profile: Profile)<br>    fun deleteAccount()<br>    fun exportData(): File<br>    fun sendPasswordReset(email: String)<br>}</pre><p>A class that only needs login and logout, such as a lightweight guest session handler, would be forced to implement or throw on four methods it has no business touching. Splitting the interface by client need keeps each contract focused.</p><pre>interface AuthActions {<br>    fun login(credentials: Credentials)<br>    fun logout()<br>}<br><br>interface ProfileActions {<br>    fun updateProfile(profile: Profile)<br>    fun exportData(): File<br>}<br><br>interface AccountManagementActions {<br>    fun deleteAccount()<br>    fun sendPasswordReset(email: String)<br>}<br><br>class GuestSessionHandler(private val authService: AuthService) : AuthActions {<br>    override fun login(credentials: Credentials) = authService.authenticate(credentials)<br>    override fun logout() = authService.clearSession()<br>}</pre><p>GuestSessionHandler now depends only on what it actually uses. If AccountManagementActions changes because of a new compliance requirement, this class does not even need to recompile.</p><h3>Dependency Inversion Principle</h3><p>High-level modules should not depend on low-level modules; both should depend on abstractions. This is the principle that makes Android’s dependency injection frameworks, such as Hilt and Koin, genuinely useful rather than ceremonial.</p><p>Without it, a ViewModel ends up tightly coupled to a concrete implementation.</p><pre>class OrderViewModel : ViewModel() {<br>    private val api = RetrofitOrderApi(RetrofitClient.instance)<br><br>    fun submitOrder(order: Order) {<br>        viewModelScope.launch {<br>            api.submit(order)<br>        }<br>    }<br>}</pre><p>Testing this ViewModel means hitting a real network client, since there is no way to substitute the dependency. Inverting the dependency means the ViewModel depends on an abstraction, and the concrete implementation is injected from outside.</p><pre>interface OrderApi {<br>    suspend fun submit(order: Order): OrderResult<br>}<br><br>class RetrofitOrderApi(private val client: OrderService) : OrderApi {<br>    override suspend fun submit(order: Order): OrderResult = client.submitOrder(order)<br>}<br><br>class OrderViewModel(private val api: OrderApi) : ViewModel() {<br>    fun submitOrder(order: Order) {<br>        viewModelScope.launch {<br>            api.submit(order)<br>        }<br>    }<br>}</pre><p>In a unit test, OrderApi can now be replaced with a fake or a mock that returns a controlled result instantly, with no network involved.</p><pre>class FakeOrderApi : OrderApi {<br>    override suspend fun submit(order: Order): OrderResult = OrderResult.Success(&quot;test-id&quot;)<br>}<br><br>@Test<br>fun `submitOrder updates state on success`() = runTest {<br>    val viewModel = OrderViewModel(FakeOrderApi())<br>    viewModel.submitOrder(sampleOrder)<br>    // assertions against viewModel state<br>}</pre><p>This is precisely why Clean Architecture on Android leans so heavily on interfaces between layers. The domain layer defines what it needs through an abstraction, and the data layer provides a concrete answer, which means your business logic can be tested and reasoned about without ever touching Retrofit, Room, or any other framework detail.</p><h3>Conclusion</h3><p>At their core, these five principles express a single idea: isolate the parts of your codebase that change for different reasons. A ViewModel that only orchestrates state, a repository that only retrieves data, an interface that promises no more than it can deliver, these are not academic exercises. They are what allows a codebase to absorb new requirements without straining at the seams.</p><p>No engineer applies all five perfectly to every class, nor should that be the goal. What matters is that the next feature request results in a smaller, safer change rather than a rewrite in disguise. The next time you review a pull request or open a class you have not touched in months, pick one principle to watch for. The rest tends to follow.</p><p>Thanks for reading!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=aa8fd05183a9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Best Practices for UI Composables in Android]]></title>
            <link>https://medium.com/@aleyvaschz/best-practices-for-ui-composables-in-android-229f3a7d6b7c?source=rss-cdc9b9b616bb------2</link>
            <guid isPermaLink="false">https://medium.com/p/229f3a7d6b7c</guid>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[performance]]></category>
            <category><![CDATA[jetpack-compose]]></category>
            <category><![CDATA[ui]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Adrian Leyva]]></dc:creator>
            <pubDate>Thu, 30 Jul 2026 15:01:02 GMT</pubDate>
            <atom:updated>2026-07-30T15:01:02.699Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*J5as9rN4Vm4cv0ZM0N6Qlg.png" /></figure><blockquote>Writing composables that stay stateless, testable, and fast.</blockquote><p>Jetpack Compose changed the way we build UI on Android, but it also introduced a new set of habits engineers need to unlearn and relearn. A composable function looks simple: it takes some parameters, emits some UI, and disappears from your mental model the moment you stop looking at it. That simplicity is deceptive. Under the hood, Compose recomposes, skips, and re-executes your functions constantly, and every design decision you make either helps or fights against that engine.</p><p>If you have ever seen a screen stutter for no obvious reason, or a composable that mysteriously ignores state updates, chances are the root cause was not Compose itself but how the composable was written. This article walks through the practices that consistently separate maintainable, performant Compose code from code that becomes a liability as the app grows.</p><h3>1. Keep Composables Stateless Whenever Possible</h3><p>The single most important principle in Compose UI design is separating stateless and stateful composables. A stateless composable receives everything it needs through parameters and reports events through callbacks. It does not know where the data comes from or what happens after an event fires.</p><pre>@Composable<br>fun ProfileHeader(<br>    name: String,<br>    isFollowing: Boolean,<br>    onFollowClick: () -&gt; Unit<br>) {<br>    Row(verticalAlignment = Alignment.CenterVertically) {<br>        Text(text = name, style = MaterialTheme.typography.titleMedium)<br>        Spacer(modifier = Modifier.width(8.dp))<br>        Button(onClick = onFollowClick) {<br>            Text(if (isFollowing) &quot;Following&quot; else &quot;Follow&quot;)<br>        }<br>    }<br>}</pre><p>This composable has no idea whether isFollowing comes from a ViewModel, a database, or a hardcoded test value. That ignorance is a feature. It makes the function trivially previewable, testable, and reusable across screens. State hoisting, the pattern of moving state up to a caller that owns it, is what makes this possible, and it should be your default approach unless a composable has a genuinely local concern, like the expanded state of a dropdown that no other part of the UI cares about.</p><h3>2. Design a Clear, Minimal Public API</h3><p>A composable is a function signature first and an implementation second. Callers should be able to understand what a composable does just by reading its parameters. Avoid passing entire data classes or ViewModels into low-level UI composables just because it is convenient. This couples your UI layer to business logic and makes previews painful.</p><pre>// Avoid<br>@Composable<br>fun UserCard(viewModel: UserViewModel) { ... }<br><br>// Prefer<br>@Composable<br>fun UserCard(<br>    user: UserUiState,<br>    onUserClick: () -&gt; Unit<br>) { ... }</pre><p>The second version can be previewed with fake data, tested without mocking a ViewModel, and reused in a different feature module without dragging in unrelated dependencies.</p><h3>3. Always Expose a Modifier Parameter</h3><p>Every public composable that emits UI should accept a Modifier parameter, default it to Modifier, and apply it to the root element. This is not a stylistic nicety, it is part of the Compose contract that lets callers control layout, padding, and behavior from the outside without needing to modify your composable&#39;s internals.</p><pre>@Composable<br>fun SectionTitle(<br>    text: String,<br>    modifier: Modifier = Modifier<br>) {<br>    Text(<br>        text = text,<br>        style = MaterialTheme.typography.titleLarge,<br>        modifier = modifier<br>    )<br>}</pre><p>A composable that ignores this convention forces every caller to wrap it in an extra container just to adjust spacing, which defeats the purpose of a composition-based UI system.</p><h3>4. Understand and Design Around Recomposition</h3><p>Recomposition is not free, and it is not magic. Compose decides whether to skip a composable based on the stability of its parameters. Passing unstable types, such as plain List or mutable classes without proper equality, can force Compose to recompose more often than necessary.</p><p>A few concrete habits help here:</p><ul><li>Prefer immutable data classes and List alternatives like ImmutableList from Kotlinx collections when working with lists in state.</li><li>Use remember to cache expensive calculations or object instances that do not need to be recreated on every recomposition.</li><li>Use derivedStateOf when a value is computed from other state but should only trigger recomposition when the computed result actually changes, not every time the source state changes.</li></ul><pre>val isButtonEnabled by remember {<br>    derivedStateOf { scrollState.value &gt; 0 }<br>}</pre><p>Without derivedStateOf, this comparison would be recalculated on every recomposition triggered by the scroll state, even when the boolean result never changes.</p><h3>5. Avoid Side Effects in the Composition Body</h3><p>Composable functions can be called, skipped, or re-executed multiple times by the Compose runtime, sometimes even out of order. Any code that produces a side effect, such as a network call, a log statement with real consequences, or writing to a shared mutable object, should never live directly in the body of a composable. Instead, use the effect APIs that Compose provides for this purpose.</p><pre>@Composable<br>fun UserProfileScreen(userId: String, viewModel: UserViewModel = viewModel()) {<br>    LaunchedEffect(userId) {<br>        viewModel.loadUser(userId)<br>    }<br>    // UI content<br>}</pre><p>LaunchedEffect ties the side effect to the composition lifecycle and automatically cancels and restarts the coroutine when the key changes. Ignoring this pattern is one of the most common sources of duplicated network calls and subtle bugs in production Compose apps.</p><h3>6. Favor Slot-Based APIs for Flexible Components</h3><p>When building reusable components meant to be shared across a codebase, slot APIs let callers inject their own composables rather than forcing a rigid structure.</p><pre>@Composable<br>fun AppCard(<br>    modifier: Modifier = Modifier,<br>    header: @Composable () -&gt; Unit,<br>    content: @Composable () -&gt; Unit<br>) {<br>    Card(modifier = modifier) {<br>        Column(modifier = Modifier.padding(16.dp)) {<br>            header()<br>            Spacer(modifier = Modifier.height(8.dp))<br>            content()<br>        }<br>    }<br>}</pre><p>This pattern, used extensively in Compose Material components like Scaffold and TopAppBar, gives you the flexibility of composition without needing dozens of boolean flags and optional parameters to cover every possible layout variant.</p><h3>7. Keep Previews Fast and Representative</h3><p>Previews are only useful if they compile quickly and reflect realistic states. Build small, focused preview functions for each meaningful UI state, rather than one giant preview that tries to cover every scenario.</p><pre>@Preview(showBackground = true)<br>@Composable<br>private fun ProfileHeaderFollowingPreview() {<br>    AppTheme {<br>        ProfileHeader(name = &quot;Adrian Leyva&quot;, isFollowing = true, onFollowClick = {})<br>    }<br>}</pre><p>Because stateless composables take plain parameters, writing previews for edge cases like empty strings, long text, or error states becomes trivial, and this is exactly where investing in state hoisting pays off again.</p><h3>8. Test Composables in Isolation</h3><p>Compose UI tests work best when the composable under test does not require a real ViewModel, repository, or navigation graph. If you followed the stateless pattern from the beginning, testing becomes a matter of setting content with fixed parameters and asserting on the resulting semantics tree.</p><pre>@Test<br>fun followButton_showsCorrectLabel_whenFollowing() {<br>    composeTestRule.setContent {<br>        ProfileHeader(name = &quot;Adrian&quot;, isFollowing = true, onFollowClick = {})<br>    }<br>    composeTestRule.onNodeWithText(&quot;Following&quot;).assertExists()<br>}</pre><p>Tests like this run fast, do not require mocking frameworks, and catch regressions in UI logic before they reach a device.</p><h3>Conclusion</h3><p>Writing good UI composables is less about memorizing Compose APIs and more about consistently applying a small set of disciplined habits: keep composables stateless and hoist state upward, design minimal and predictable public APIs, always expose a Modifier parameter, respect the recomposition model instead of fighting it, and push side effects into the proper lifecycle-aware APIs. None of these practices are exotic, but together they are what separates a Compose codebase that scales gracefully from one that becomes fragile as the team and the feature set grow.</p><p>The investment pays off quickly. Composables built this way are easier to preview, easier to test, easier to reuse across features, and far less likely to produce the kind of subtle recomposition bugs that are notoriously hard to track down. As your app grows, these habits are what keep your UI layer maintainable instead of becoming a source of technical debt.</p><p>Thanks for reading!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=229f3a7d6b7c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Content Provider in Android — Sharing Data Safely Across App Boundaries]]></title>
            <link>https://medium.com/@aleyvaschz/content-provider-in-android-sharing-data-safely-across-app-boundaries-7601ebeb1cbc?source=rss-cdc9b9b616bb------2</link>
            <guid isPermaLink="false">https://medium.com/p/7601ebeb1cbc</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[android-app-development]]></category>
            <dc:creator><![CDATA[Adrian Leyva]]></dc:creator>
            <pubDate>Wed, 29 Jul 2026 15:01:04 GMT</pubDate>
            <atom:updated>2026-07-29T15:01:04.168Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qLhhGQimcz93ojbbNWsUdg.jpeg" /></figure><blockquote>Understanding Android’s most misunderstood component</blockquote><p>If you have been writing Android apps for more than a few months, you have used a Content Provider without realizing it. Every time you pick a contact, select a photo from the gallery, or read a file through a document picker, a Content Provider is working behind the scenes. Yet when developers are asked to explain what it actually is, most answers are vague at best.</p><p>This article breaks down what a Content Provider really is, how it works internally, when you should reach for one, and how to build a simple one.</p><h3>What Is a Content Provider</h3><p>A Content Provider is one of the four fundamental Android components, alongside Activity, Service, and Broadcast Receiver. Its job is to manage access to a structured set of data and expose it to other applications, or even to different modules within your own app, through a consistent and secure interface.</p><p>Think of it as a small internal API. Instead of exposing HTTP endpoints, it exposes URIs. Instead of JSON responses, it returns Cursor objects (or, more recently, structures wrapped around them). The consumer does not need to know if your data lives in a SQLite database, a Room database, a set of files, or an in memory structure. It only needs to know the URI and the contract.</p><p>This decoupling is the whole point. A Content Provider hides the storage implementation and exposes a stable data access layer.</p><h3>Why It Exists</h3><p>Android enforces strong sandboxing between apps. One app cannot simply reach into another app’s SQLite database or file system. That would be a massive security hole. The Content Provider is Android’s official, permission controlled door between that sandbox and the outside world.</p><p>So the real motivation is twofold:</p><ul><li>Sharing data safely between apps (Contacts, MediaStore, Calendar, and so on).</li><li>Providing a uniform data access abstraction, even inside a single app, particularly useful for components like widgets, Slices, or search suggestions that rely on Content Providers by design.</li></ul><h3>How It Works Internally</h3><p>A Content Provider revolves around four concepts: the URI, the Contract, the ContentResolver, and the Provider implementation itself.</p><h4>The URI</h4><p>Every piece of data exposed by a provider is identified by a URI, following this pattern: <strong><em>content://authority/path/id</em></strong></p><p>For example:</p><pre>content://com.android.contacts/contacts/45</pre><p>The authority uniquely identifies the provider on the device, usually matching your app’s package name to avoid collisions.</p><h4>The ContentResolver</h4><p>Client apps never talk to the provider directly. They talk to a ContentResolver, which acts as a router. It looks at the authority in the URI, finds the matching registered provider, and forwards the call.</p><pre>val cursor = context.contentResolver.query(<br>    contactUri,<br>    projection,<br>    selection,<br>    selectionArgs,<br>    sortOrder<br>)</pre><p>This indirection is important. It means the calling app never needs a direct reference to the provider class, only the URI and permissions.</p><h4>The Provider Implementation</h4><p>On the other side, you extend ContentProvider and implement six core methods:</p><pre>class NotesProvider : ContentProvider() {<br><br>    private lateinit var dbHelper: NotesDbHelper<br><br>    override fun onCreate(): Boolean {<br>        dbHelper = NotesDbHelper(context!!)<br>        return true<br>    }<br><br>    override fun query(<br>        uri: Uri,<br>        projection: Array&lt;String&gt;?,<br>        selection: String?,<br>        selectionArgs: Array&lt;String&gt;?,<br>        sortOrder: String?<br>    ): Cursor {<br>        val db = dbHelper.readableDatabase<br>        return db.query(&quot;notes&quot;, projection, selection, selectionArgs, null, null, sortOrder)<br>    }<br><br>    override fun insert(uri: Uri, values: ContentValues?): Uri {<br>        val db = dbHelper.writableDatabase<br>        val id = db.insert(&quot;notes&quot;, null, values)<br>        context?.contentResolver?.notifyChange(uri, null)<br>        return Uri.withAppendedPath(uri, id.toString())<br>    }<br><br>    override fun update(<br>        uri: Uri,<br>        values: ContentValues?,<br>        selection: String?,<br>        selectionArgs: Array&lt;String&gt;?<br>    ): Int {<br>        val db = dbHelper.writableDatabase<br>        val count = db.update(&quot;notes&quot;, values, selection, selectionArgs)<br>        context?.contentResolver?.notifyChange(uri, null)<br>        return count<br>    }<br><br>    override fun delete(uri: Uri, selection: String?, selectionArgs: Array&lt;String&gt;?): Int {<br>        val db = dbHelper.writableDatabase<br>        val count = db.delete(&quot;notes&quot;, selection, selectionArgs)<br>        context?.contentResolver?.notifyChange(uri, null)<br>        return count<br>    }<br><br>    override fun getType(uri: Uri): String = &quot;vnd.android.cursor.dir/notes&quot;<br>}</pre><p>And you declare it in the manifest:</p><pre>&lt;provider<br>    android:name=&quot;.NotesProvider&quot;<br>    android:authorities=&quot;com.example.notes.provider&quot;<br>    android:exported=&quot;false&quot; /&gt;</pre><p>Setting exported to false restricts access to your own app unless you explicitly grant permissions elsewhere. This single attribute is one of the most common security mistakes: leaving a provider exported when it was never meant to be public.</p><h4>UriMatcher</h4><p>Real providers usually deal with several URI shapes: a full table, a single row, a related sub resource. UriMatcher makes routing manageable:</p><pre>private val uriMatcher = UriMatcher(UriMatcher.NO_MATCH).apply {<br>    addURI(&quot;com.example.notes.provider&quot;, &quot;notes&quot;, NOTES)<br>    addURI(&quot;com.example.notes.provider&quot;, &quot;notes/#&quot;, NOTE_ID)<br>}</pre><p>Inside query, update, or delete, you switch on the match result to decide how to build the SQL selection clause.</p><h3>Use Cases</h3><p>You do not need a Content Provider for every local database. Room alone is enough for most single app scenarios. A Content Provider becomes the right tool when:</p><ul><li><strong>You need to share data with other apps.</strong> <br>A document scanner app exposing scanned files to a viewer app, for example.</li><li><strong>You integrate with system components that expect one.</strong> <br>Widgets, Slices, autofill services, and search suggestion providers are all designed around this contract.</li><li><strong>You need fine grained, URI based permissions.</strong> <br>You can grant temporary read or write access to a specific URI using grantUriPermission, without exposing your entire dataset. This is exactly how sharing a single photo through FileProvider works.</li><li><strong>You want a stable abstraction over changing storage.</strong> <br>If your data source might migrate from SQLite to a remote cache later, a provider shields consumers from that change.</li></ul><p>A very common real world example is FileProvider, a specialized subclass provided by AndroidX for sharing files securely between apps without exposing raw file paths:</p><pre>val uri = FileProvider.getUriForFile(<br>    context,<br>    &quot;${context.packageName}.fileprovider&quot;,<br>    imageFile<br>)</pre><pre>val intent = Intent(Intent.ACTION_SEND).apply {<br>    putExtra(Intent.EXTRA_STREAM, uri)<br>    addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)<br>    type = &quot;image/jpeg&quot;<br>}</pre><p>Notice the flag FLAG_GRANT_READ_URI_PERMISSION. It grants temporary access to that specific URI to whichever app receives the intent, without making the provider publicly exported.</p><h3>Content Provider vs Room vs Repository</h3><p>A common point of confusion is thinking Content Provider competes with Room or with the Repository pattern. It does not, since they solve different problems. Room is a persistence library focused on local storage. Repository is an architectural pattern focused on abstracting data sources from the rest of your app. Content Provider is an interprocess communication mechanism focused on exposing data across process or app boundaries.</p><p>You can combine all three: Room manages storage, a Repository coordinates access inside your app, and a Content Provider exposes a subset of that data to the outside world when needed.</p><h3>Conclusion</h3><p>A Content Provider is Android’s answer to controlled, cross process data sharing. It wraps your storage layer behind a stable URI based contract, routes every request through the ContentResolver, and lets you define exactly how much of your data other components or apps can see. You will rarely need to build one from scratch for a typical app, but understanding how it works is essential once you deal with system integrations, file sharing, or building components that other apps or system surfaces will consume.</p><p>Thanks for reading!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7601ebeb1cbc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Offline-First Architecture in Android — Building Apps That Never Stop Working]]></title>
            <link>https://medium.com/@aleyvaschz/offline-first-architecture-in-android-building-apps-that-never-stop-working-08227cb0f1a0?source=rss-cdc9b9b616bb------2</link>
            <guid isPermaLink="false">https://medium.com/p/08227cb0f1a0</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[offline-first]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <dc:creator><![CDATA[Adrian Leyva]]></dc:creator>
            <pubDate>Mon, 27 Jul 2026 15:01:03 GMT</pubDate>
            <atom:updated>2026-07-27T15:01:03.410Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Dd9u93wGNk1MoHmW8IODDw.jpeg" /></figure><blockquote>Designing resilient data layers with Room, DataStore, and a synchronization strategy that survives real-world connectivity</blockquote><p>Picture this, an user opens your app in a subway tunnel, a rural area with spotty coverage, or an airplane without Wi-Fi. If your app freezes, shows a blank screen, or worse, loses the data they just entered, you have lost their trust. In a world where connectivity is assumed but rarely guaranteed, offline-first architecture is no longer a nice-to-have. It is a fundamental design decision that separates resilient, professional applications from fragile ones.</p><p>Offline-first is not simply about caching a few API responses. It is a philosophy that treats the local database as the primary source of data, with the network acting as a background synchronization layer rather than a hard dependency. In this article, we will explore how to implement this approach in Android using Room and DataStore as your Single Source of Truth, along with practical strategies for synchronization and conflict resolution.</p><h3>What Offline-First Really Means</h3><p>In a traditional online-first app, the network is the source of truth. The UI requests data from an API, waits for a response, and renders it. If the request fails, the user sees an error or a spinner. This model works fine in ideal conditions, but it breaks down the moment connectivity becomes unreliable.</p><p>Offline-first flips this relationship. The local database becomes the authority the UI always reads from. The network’s job is to keep that local database updated in the background, not to serve data directly to the screen. This means your app remains fully functional, readable, and even writable, regardless of connection status. When the network eventually becomes available, changes sync silently.</p><p>This shift has a significant architectural implication: your app needs a clear, disciplined data layer that can reconcile local and remote states without corrupting the user’s experience.</p><h3>Single Source of Truth: Room and DataStore</h3><p>The Single Source of Truth (SSOT) pattern is the backbone of offline-first design. It states that at any given moment, there should be one authoritative place where the current state of a piece of data lives. Every other layer, whether it is the UI, ViewModel, or repository, only observes that source. It never queries the network directly for display purposes.</p><p>In Android, this authoritative layer is typically implemented with two tools working together:</p><p><strong>Room</strong> handles structured, relational data: user records, messages, orders, or any entity with multiple fields and relationships. Room exposes data through Flow, which means your UI automatically reacts to database changes without any manual refresh logic. When a background sync operation updates a row, the UI updates itself.</p><p><strong>DataStore</strong> is better suited for simpler, key-value data: user preferences, feature flags, authentication tokens, or lightweight settings. Unlike SharedPreferences, DataStore is asynchronous by design and integrates naturally with Kotlin Coroutines and Flow, which keeps it consistent with the reactive nature of Room.</p><p>A typical repository built around SSOT looks like this conceptually:</p><ul><li>The ViewModel observes a Flow exposed by the Repository.</li><li>The Repository reads exclusively from Room (or DataStore for simple data).</li><li>A separate synchronization mechanism, usually a WorkManager job or a coroutine-based sync engine, fetches remote data and writes it into Room.</li><li>Room emits the update through Flow, and the UI reflects it automatically.</li></ul><p>The critical rule here is that the UI layer never talks to the network directly. This isolation is what makes offline-first apps predictable, the screen always shows what is in the database, and the database is always the most recent known truth, whether that truth came from a previous sync or a local, unsynced edit made by the user.</p><p>Here is a minimal Room entity with the sync metadata mentioned above, followed by the DAO exposing it as a Flow:</p><pre>@Entity(tableName = &quot;notes&quot;)<br>data class NoteEntity(<br>    @PrimaryKey val id: String,<br>    val title: String,<br>    val content: String,<br>    val lastModified: Long,<br>    val isSynced: Boolean = false,<br>    val pendingOperation: String? = null // &quot;CREATE&quot;, &quot;UPDATE&quot;, &quot;DELETE&quot;<br>)<br><br>@Dao<br>interface NoteDao {<br>    @Query(&quot;SELECT * FROM notes WHERE pendingOperation IS NULL OR pendingOperation != &#39;DELETE&#39;&quot;)<br>    fun observeNotes(): Flow&lt;List&lt;NoteEntity&gt;&gt;<br><br>    @Query(&quot;SELECT * FROM notes WHERE isSynced = 0&quot;)<br>    suspend fun getUnsyncedNotes(): List&lt;NoteEntity&gt;<br><br>    @Upsert<br>    suspend fun upsert(note: NoteEntity)<br><br>    @Query(&quot;UPDATE notes SET isSynced = 1, pendingOperation = NULL WHERE id = :id&quot;)<br>    suspend fun markAsSynced(id: String)<br>}</pre><p>For simpler key-value data, such as the timestamp of the last successful sync, DataStore fits naturally:</p><pre>private val Context.dataStore by preferencesDataStore(name = &quot;app_settings&quot;)<br><br>class SyncPreferences(private val context: Context) {<br>    private val LAST_SYNC_KEY = longPreferencesKey(&quot;last_sync_timestamp&quot;)<br><br>    val lastSyncTimestamp: Flow&lt;Long&gt; = context.dataStore.data<br>        .map { prefs -&gt; prefs[LAST_SYNC_KEY] ?: 0L }<br><br>    suspend fun updateLastSync(timestamp: Long) {<br>        context.dataStore.edit { prefs -&gt; prefs[LAST_SYNC_KEY] = timestamp }<br>    }<br>}</pre><p>The Repository ties both together and is the only component the ViewModel ever talks to:</p><pre>class NoteRepository(<br>    private val dao: NoteDao,<br>    private val api: NoteApi,<br>    private val syncPrefs: SyncPreferences<br>) {<br>    // Single Source of Truth: the UI only ever observes Room<br>    fun observeNotes(): Flow&lt;List&lt;NoteEntity&gt;&gt; = dao.observeNotes()<br><br>    suspend fun saveNote(note: NoteEntity) {<br>        dao.upsert(note.copy(isSynced = false, pendingOperation = &quot;UPDATE&quot;))<br>    }<br>}</pre><h3>Designing the Synchronization Layer</h3><p>Synchronization is where most of the real engineering effort goes. A robust sync strategy generally follows one of two patterns, and many production apps use a hybrid of both.</p><p><strong>Pull-based sync</strong> fetches data from the server on a schedule, on app launch, or when connectivity is restored. This works well for data that changes independently of the user’s actions, such as a news feed or product catalog. WorkManager is the standard tool here, since it guarantees execution even if the app is closed, respects battery and network constraints, and can be configured with retry policies and backoff strategies.</p><p><strong>Push-based sync</strong>, often implemented through mechanisms like Firebase Cloud Messaging or WebSockets, notifies the client that new data is available, triggering an immediate local update. This reduces latency but adds infrastructure complexity, and it should still be backed by a periodic pull-based fallback to handle missed notifications.</p><p>Regardless of which pattern you choose, every local write made while offline needs to be tracked. A common technique is to add metadata columns to your Room entities, such as isSynced, lastModified, or pendingOperation(create, update, delete). When the device regains connectivity, a sync worker queries for all unsynced records and pushes them to the server in order, then marks them as synced upon confirmation.</p><p>This queue-based approach, sometimes implemented as an outbox pattern, ensures that no user action is silently lost, even if the app is killed mid-sync. WorkManager’s persistence guarantees make it a natural fit for this responsibility.</p><p>A simplified sync worker that drains the outbox and pulls remote updates might look like this:</p><pre>class SyncWorker(<br>    context: Context,<br>    params: WorkerParameters,<br>    private val dao: NoteDao,<br>    private val api: NoteApi<br>) : CoroutineWorker(context, params) {<br><br>    override suspend fun doWork(): Result {<br>        return try {<br>            // 1. Push local, unsynced changes first<br>            val pending = dao.getUnsyncedNotes()<br>            pending.forEach { note -&gt;<br>                when (note.pendingOperation) {<br>                    &quot;DELETE&quot; -&gt; api.deleteNote(note.id)<br>                    else -&gt; api.upsertNote(note.toDto())<br>                }<br>                dao.markAsSynced(note.id)<br>            }<br><br>            // 2. Pull the latest remote state<br>            val remoteNotes = api.fetchNotes()<br>            remoteNotes.forEach { remote -&gt;<br>                dao.upsert(remote.toEntity(isSynced = true))<br>            }<br><br>            Result.success()<br>        } catch (e: IOException) {<br>            Result.retry()<br>        }<br>    }<br>}<br><br>// Scheduling a periodic, constraint-aware sync<br>val syncRequest = PeriodicWorkRequestBuilder&lt;SyncWorker&gt;(30, TimeUnit.MINUTES)<br>    .setConstraints(<br>        Constraints.Builder()<br>            .setRequiredNetworkType(NetworkType.CONNECTED)<br>            .build()<br>    )<br>    .setBackoffCriteria(BackoffPolicy.EXPONENTIAL, 10, TimeUnit.SECONDS)<br>    .build()<br><br>WorkManager.getInstance(context)<br>    .enqueueUniquePeriodicWork(&quot;note_sync&quot;, ExistingPeriodicWorkPolicy.KEEP, syncRequest)</pre><h3>Handling Conflicts</h3><p>Conflicts are the inevitable consequence of allowing offline writes. If a user edits a record on their phone while offline, and that same record is modified on the server by another device or user, your app needs a deterministic way to decide which version wins.</p><p>There is no universal answer here; the right strategy depends on your domain. That said, a few well-established approaches cover most real-world cases:</p><p><strong>Last-Write-Wins (LWW):</strong> resolves conflicts by comparing timestamps and keeping whichever version was modified most recently. It is simple to implement and works well for data where losing minor edits is an acceptable trade-off, such as personal notes or settings. Its main weakness is that it can silently discard a user’s legitimate change if their clock or sync timing is unfavorable.</p><p><strong>Server-authoritative resolution</strong> :treats the backend as the final decision-maker. The client submits its local changes, and the server applies business logic to determine the outcome, then pushes the resolved state back down. This is appropriate for data with strict business rules, such as inventory counts or financial transactions, where arbitrary client-side timestamps are not a safe basis for truth.</p><p><strong>Field-level merging:</strong> goes a step further by resolving conflicts at the level of individual fields rather than entire records. If two users edit different fields of the same object while offline, both changes can be preserved instead of one overwriting the other. This requires more sophisticated tracking, often using version vectors or per-field timestamps, but it produces the best user experience for collaborative data.</p><p><strong>Manual conflict resolution:</strong> surfaces the conflict to the user directly, letting them choose which version to keep. This is common in productivity apps like note-taking or document editors, where automated resolution risks losing something the user cares about.</p><p>Whichever strategy you adopt, it should be implemented consistently in your Repository layer, not scattered across ViewModels or UI code. Keeping conflict resolution logic centralized makes it testable and easier to reason about as your data model evolves.</p><p>Here is a simple Last-Write-Wins resolver used when merging a remote record with a local, unsynced one:</p><pre>fun resolveConflict(local: NoteEntity, remote: NoteEntity): NoteEntity {<br>    return if (local.pendingOperation != null &amp;&amp; local.lastModified &gt; remote.lastModified) {<br>        // The local edit is newer and still unsynced: keep it, mark for re-push<br>        local.copy(isSynced = false)<br>    } else {<br>        // The remote version wins: accept it and clear any pending flag<br>        remote.copy(isSynced = true, pendingOperation = null)<br>    }<br>}</pre><p>For domains where losing an edit is not acceptable, a manual resolution flow can expose both versions to the user instead of resolving silently:</p><pre>sealed class ConflictResult {<br>    data class Resolved(val note: NoteEntity) : ConflictResult()<br>    data class RequiresUserInput(val local: NoteEntity, val remote: NoteEntity) : ConflictResult()<br>}<br><br>fun evaluateConflict(local: NoteEntity, remote: NoteEntity): ConflictResult {<br>    val bothEdited = local.pendingOperation != null &amp;&amp; local.lastModified != remote.lastModified<br>    return if (bothEdited) {<br>        ConflictResult.RequiresUserInput(local, remote)<br>    } else {<br>        ConflictResult.Resolved(resolveConflict(local, remote))<br>    }<br>}</pre><h3>Putting It All Together</h3><p>A well-structured offline-first Android app generally follows this layered flow:</p><p>The UI observes Flow from the Repository. The Repository reads only from Room and DataStore, which serve as the Single Source of Truth. A synchronization engine, built with WorkManager and Coroutines, periodically reconciles local and remote state, applying your chosen conflict resolution strategy. Local writes are tracked with sync metadata so nothing is lost between connectivity windows.</p><p>This architecture is more demanding to build than a simple online-only app, but the payoff is substantial, your app becomes resilient to network conditions, feels instantaneous to the user because reads never wait on the network, and scales gracefully as your data and user base grow.</p><h3>Conclusion</h3><p>Offline-first architecture reframes how we think about mobile applications. Instead of treating the network as a dependency the app cannot function without, it treats connectivity as an enhancement that keeps local data fresh. By combining Room and DataStore as your Single Source of Truth, designing a disciplined synchronization layer with WorkManager, and choosing a conflict resolution strategy that fits your domain, you can build Android applications that remain fast, reliable, and trustworthy no matter what the network is doing.</p><p>The investment is real, but so is the outcome, an app that respects the user’s time and data, whether they are on fiber, on a weak cellular signal, or completely offline.</p><p>Thanks for reading!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=08227cb0f1a0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Jetpack Compose Performance — What actually causes janky performance]]></title>
            <link>https://medium.com/@aleyvaschz/jetpack-compose-performance-what-actually-causes-janky-performance-8b8207ece0c8?source=rss-cdc9b9b616bb------2</link>
            <guid isPermaLink="false">https://medium.com/p/8b8207ece0c8</guid>
            <category><![CDATA[ui]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[jetpack-compose]]></category>
            <category><![CDATA[performance]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Adrian Leyva]]></dc:creator>
            <pubDate>Wed, 22 Jul 2026 20:25:58 GMT</pubDate>
            <atom:updated>2026-07-22T20:25:58.105Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*LrX-ihtOGVoRRuGXi00NCQ@2x.jpeg" /></figure><h2>Jetpack Compose Performance — What actually causes janky performance</h2><blockquote>A hands on look at recomposition, state stability, and lazy list performance in Compose.</blockquote><p>Jetpack Compose has changed how Android developers build UI. The declarative model is easier to reason about than the old View system, but that same flexibility can hide performance problems if you are not careful. Recomposition, unstable parameters, and heavy work inside composables can quietly turn a smooth app into a laggy one.</p><p>In this article, we will walk through how Compose decides what to redraw, the most common performance traps, and practical patterns you can apply today. Each section includes code examples so you can see the difference between a naive approach and an optimized one.</p><h3><strong>How Recomposition Actually Works</strong></h3><p>Compose rebuilds the UI by calling composable functions again when the state they read changes. This process is called recomposition. The Compose compiler tries to skip recomposing a composable if its inputs have not changed, but it can only do that if those inputs are considered stable.</p><p>A type is stable when Compose can guarantee that if its value does not change, its public properties will not change either. Primitive types, strings, and immutable data classes with val properties are stable. Mutable collections like MutableList are not, because Compose cannot prove their contents stay the same between calls.</p><pre>// Unstable: List is a mutable interface, Compose cannot trust it<br>data class UserState(val users: List&lt;User&gt;)<br><br>// Stable: use an immutable collection or wrap it<br>data class UserState(val users: ImmutableList&lt;User&gt;)</pre><p>You can check whether your composables are skippable by enabling the Compose compiler metrics. This generates reports showing which functions are stable, unstable, or restartable.</p><pre>// build.gradle.kts<br>composeCompiler {<br>    reportsDestination = layout.buildDirectory.dir(&quot;compose_compiler&quot;)<br>    metricsDestination = layout.buildDirectory.dir(&quot;compose_compiler&quot;)<br>}</pre><p>Running a build with these flags produces a report you can scan for red flags, especially composables marked unstable that appear deep in your list or grid hierarchies.</p><h3>Performance techniques</h3><p>Some techniques and advices you can implement when working with Jetpack Compose.</p><h4>Avoid Unnecessary Recomposition with Stable Parameters</h4><pre>// Bad: a new lambda is created every recomposition<br>@Composable<br>fun UserRow(user: User, onClick: (User) -&gt; Unit) {<br>    Text(<br>        text = user.name,<br>        modifier = Modifier.clickable { onClick(user) }<br>    )<br>}<br><br>@Composable<br>fun UserList(users: List&lt;User&gt;) {<br>    LazyColumn {<br>        items(users) { user -&gt;<br>            UserRow(user = user, onClick = { selected -&gt; println(selected) })<br>        }<br>    }<br>}</pre><p>Hoisting the lambda and using remember prevents the lambda from being rebuilt unnecessarily, and keeps the item composable skippable.</p><pre>@Composable<br>fun UserList(users: List&lt;User&gt;) {<br>    val onUserClick = remember {<br>        { user: User -&gt; println(user) }<br>    }<br><br>    LazyColumn {<br>        items(users, key = { it.id }) { user -&gt;<br>            UserRow(user = user, onClick = onUserClick)<br>        }<br>    }<br>}</pre><p>Notice the key parameter in items. Without it, Compose uses item position as identity, which causes unnecessary recompositions and broken animations when the list is reordered or filtered. Always supply a stable, unique key.</p><h4>State Reads and the derivedStateOf Trap</h4><p>Reading state inside a composable ties that composable to recomposition whenever the state changes, even if the visible output does not actually change. A classic example is calculating a boolean from a scroll position.</p><pre>// Bad: recomposes on every pixel of scroll<br>@Composable<br>fun ScrollToTopButton(listState: LazyListState) {<br>    val showButton = listState.firstVisibleItemIndex &gt; 0<br>    if (showButton) {<br>        FloatingActionButton(onClick = { /* scroll up */ }) {<br>            Icon(Icons.Default.ArrowUpward, contentDescription = null)<br>        }<br>    }<br>}</pre><p>Wrapping the calculation in derivedStateOf tells Compose to only trigger recomposition when the derived boolean value actually flips, not on every intermediate state change.</p><pre>@Composable<br>fun ScrollToTopButton(listState: LazyListState) {<br>    val showButton by remember {<br>        derivedStateOf { listState.firstVisibleItemIndex &gt; 0 }<br>    }<br>    if (showButton) {<br>        FloatingActionButton(onClick = { /* scroll up */ }) {<br>            Icon(Icons.Default.ArrowUpward, contentDescription = null)<br>        }<br>    }<br>}</pre><p>This pattern is especially useful for scroll listeners, drag gestures, and any calculation derived from rapidly changing state.</p><h4>Lazy Lists: Keys, Content Types, and Item Reuse</h4><p>LazyColumn and LazyRow only compose the items currently visible on screen, which is already a huge win over rendering everything at once. But you can still make lazy lists slower than they need to be.</p><p>Always provide both a key and a contentType when your list has mixed item shapes. The contentType lets Compose reuse a composition slot across items of the same visual shape, reducing the cost of creating new nodes as the user scrolls.</p><pre>LazyColumn {<br>    items(<br>        items = feedItems,<br>        key = { it.id },<br>        contentType = { it.type }<br>    ) { item -&gt;<br>        when (item) {<br>            is FeedItem.Post -&gt; PostCard(item)<br>            is FeedItem.Ad -&gt; AdCard(item)<br>            is FeedItem.Suggestion -&gt; SuggestionCard(item)<br>        }<br>    }<br>}</pre><p>Avoid putting expensive calculations, like formatting dates or resizing images, directly in the item composable. Precompute that data once when the list is built, so scrolling does not repeatedly trigger the same work.</p><h4>Heavy Work Belongs Outside Composition</h4><p>Composable functions can be called many times, sometimes on every frame during an animation. Any expensive computation, network call, or database query inside a composable body is a red flag.</p><pre>// Bad: parses and formats on every recomposition<br>@Composable<br>fun OrderSummary(order: Order) {<br>    val formattedTotal = NumberFormat.getCurrencyInstance().format(order.total)<br>    Text(formattedTotal)<br>}</pre><p>For pure calculations that depend on unchanging inputs, remember is usually enough. For anything involving coroutines, use LaunchedEffect scoped to the relevant key so the work only reruns when necessary.</p><pre>@Composable<br>fun OrderSummary(order: Order) {<br>    val formattedTotal = remember(order.total) {<br>        NumberFormat.getCurrencyInstance().format(order.total)<br>    }<br>    Text(formattedTotal)<br>}<br><br>@Composable<br>fun OrderDetails(orderId: String, viewModel: OrderViewModel) {<br>    LaunchedEffect(orderId) {<br>        viewModel.loadOrder(orderId)<br>    }<br>}</pre><h3>Conclusion</h3><p>Jetpack Compose gives you a lot of power, but that power comes with the responsibility to understand how recomposition works under the hood. The core ideas covered here are worth repeating: keep your state stable, hoist lambdas, defer reads to the smallest possible scope, use derivedStateOf for calculated values, supply keys and content types in lazy lists, and keep heavy work out of composition entirely.</p><p>None of these techniques require a rewrite. They are small, targeted changes you can apply incrementally as you profile your app and find real bottlenecks. Start with the Compose compiler metrics report and the Layout Inspector to find where your app is actually spending its recomposition budget, then apply the pattern that fits. Performance work is most effective when it is guided by data, not guesses, and Compose gives you the tools to get that data if you know where to look.</p><p>Thanks for reading!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8b8207ece0c8" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>