<?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 Davies Adedayo AbdulGafar on Medium]]></title>
        <description><![CDATA[Stories by Davies Adedayo AbdulGafar on Medium]]></description>
        <link>https://medium.com/@SirDavies?source=rss-20e877f606ea------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*bNNwStY8m2-vG2cG</url>
            <title>Stories by Davies Adedayo AbdulGafar on Medium</title>
            <link>https://medium.com/@SirDavies?source=rss-20e877f606ea------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 00:18:50 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@SirDavies/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[Rethinking Networking in Android (Turning Android Repositories into Composable Effects)]]></title>
            <link>https://proandroiddev.com/rethinking-networking-in-android-turning-android-repositories-into-composable-effects-3e9310687a8b?source=rss-20e877f606ea------2</link>
            <guid isPermaLink="false">https://medium.com/p/3e9310687a8b</guid>
            <category><![CDATA[functional-programming]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[androiddev]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[repository-design-pattern]]></category>
            <dc:creator><![CDATA[Davies Adedayo AbdulGafar]]></dc:creator>
            <pubDate>Mon, 17 Aug 2026 13:26:16 GMT</pubDate>
            <atom:updated>2026-08-17T13:26:16.627Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*08rFY5zR47rSs0XypKNldA.png" /><figcaption>Compose Steps</figcaption></figure><h3>The Repository That Forgot Its Purpose</h3><p>Imagine you are building a feature that needs to fetch a user, create a post on their behalf, upload an attachment, and finally notify them that everything succeeded. In most Android applications, this workflow quickly becomes a chain of repository calls, temporary variables, nested try/catch blocks, and orchestration code spread across use cases or ViewModels. Repositories, despite their name, often become little more than wrappers around Retrofit or Room objects that expose CRUD operations while hiding the implementation details of the underlying data source.</p><p>But what if a repository wasn’t a storage abstraction at all? What if, instead of representing <em>where data comes from</em>, it represented <em>a computation that knows how to produce data, propagate failures, and compose with future network operations</em>? In that world, a repository is no longer a collection of methods like getUser() or createPost(). It becomes a computation that can be transformed, chained, retried, and executed only when needed, allowing complex networking workflows to be expressed as a single, composable pipeline.</p><p>This article explores that idea. We’ll rethink the traditional Repository pattern and gradually transform it into an abstraction that carries not only values and failures, but also the networking environment required to continue executing requests. The result is an architecture that eliminates much of the boilerplate surrounding orchestration, centralizes concerns like retries and error handling, and makes networking code read more like a description of a workflow than a sequence of imperative steps.</p><h3>What If a Repository Was a Computation?</h3><p>Before we can transform a repository into a computation, we need to answer a more fundamental question:</p><blockquote><em>What exactly is a computation?</em></blockquote><p>In mathematics, a computation can be thought of as a process that consumes some input, performs a series of transformations, and eventually produces either a value or an error. The details of how that work is performed are often less important than the objects participating in the computation and the rules that govern how they interact.</p><p>If we look at a typical networking workflow, three fundamental objects emerge:</p><ol><li>A value that may succeed or fail.</li><li>A set of operations that the backend is capable of performing.</li><li>A mechanism for translating transport-specific data into domain concepts.</li></ol><p>Together, these form the foundation upon which the rest of the architecture is built.</p><h4>Values and Failures</h4><p>Every network request has two possible outcomes: it either succeeds and produces data, or it fails and produces an error.</p><p>Instead of representing these possibilities with exceptions, we can model them explicitly using a Result type — specifically, the Result&lt;V, E&gt; from the com.github.michaelbull.result library, which gives us Ok/Err construction plus map/flatMap combinators for free.</p><pre>Result&lt;User, NetworkError&gt;</pre><p>This type tells us that a computation may produce a User, or it may produce a NetworkError.</p><p>More importantly, it gives us a predictable structure that can be transformed and composed. Rather than scattering try/catch blocks throughout the application, failure becomes part of the type system itself.</p><p>From this perspective, a network request is not a function that returns a value. It is a computation that returns a Result.</p><h4>Capabilities Instead of Endpoints</h4><p>The second building block is the set of operations available to the computation. Traditional networking layers often expose a large collection of service methods:</p><pre>interface UserService {<br>    suspend fun getUser(id: String): UserDto    <br>    suspend fun createUser(request: CreateUserRequest): UserDto<br>}<br><br>interface PostService {...}<br><br>interface AuthService {...}</pre><p>This approach models the backend in terms of concrete endpoints. Our architecture instead models the backend in terms of capabilities:</p><pre>sealed interface Api<br><br>interface Get : Api {<br>    suspend fun getUser(id: String): Users.User<br>    suspend fun getPosts(): List&lt;Posts.Post&gt;<br>}<br><br>interface Post : Api {<br>    suspend fun createUser(request: UserCreateRequest): Users.User<br>    suspend fun createPost(request: PostCreateRequest): Posts.Post<br>}<br>// Put.kt, Delete.kt, Patch.kt follow the same pattern - and, like Post, extend Api.</pre><p>Notice the subtle difference. The interfaces are no longer describing a particular service implementation. They are describing what operations are possible.</p><p>Mathematically, they define the environment in which a computation can execute. A computation that requires Get capability can perform read operations. A computation that requires Post capability can perform write operations. The computation itself does not need to know whether those capabilities are implemented using Retrofit, Ktor, or a test double. It only needs to know that the capability exists.</p><p>One naming detail is worth calling out explicitly, because it isn’t obvious until you hit it: Users.User and Posts.Post are qualified on purpose, not for decoration. If you declare interface Post : Api and, elsewhere in the same file or package, a plain data class Post(...) domain model, Kotlin rejects the program outright:</p><pre>error: redeclaration:<br>interface Post : Api<br>data class Post(val id: String, val title: String)</pre><p>The HTTP-verb capability and the domain noun it eventually returns want the same short name, and only one of them can have it. Wrapping the domain models in small namespacing objects (object Users { data class User(...) }, object Posts { data class Post(...) }) sidesteps the collision entirely and costs nothing at the call site beyond the extra qualifier.</p><h4>Domain Concepts Over Transport Objects</h4><p>The final building block is the distinction between transport data and business data. Network responses are often shaped by the backend:</p><pre>{  &quot;id&quot;: 42,  &quot;name&quot;: &quot;John Doe&quot;}</pre><p>These structures exist to satisfy an API contract, not to model the business domain. For that reason, the architecture separates DTOs from domain models.</p><pre>data class UserResponse(val id: Int, val name: String) : DomainModel&lt;Users.User&gt;</pre><pre>object Users {<br>    data class User(val name: String)<br>}</pre><p>The DTO is responsible for translating itself into a domain representation:</p><pre>override fun toDomain(): Users.User { return Users.User(name) }</pre><p>This allows every computation to operate on domain concepts rather than transport-specific structures.</p><p>As computations are composed together, DTOs disappear and domain models remain.</p><h4>From Objects to Computations</h4><p>At this point we have all the ingredients necessary to describe a computation:</p><ul><li>A value that may succeed or fail (Result)</li><li>An environment that provides capabilities (Api, Get, Post, ...)</li><li>A way to transform transport data into domain concepts (DomainModel)</li></ul><p>What we do not yet have is a way to connect computations together. How does the output of one network request become the input of the next? How do failures automatically short-circuit an entire workflow? How does the networking environment flow through the chain without being passed around explicitly?</p><p>To answer those questions, we need one more abstraction: an <strong>effect</strong>.</p><h3>The Missing Abstraction: Effects</h3><p>By themselves, the three building blocks we introduced are not enough to model a networking workflow.</p><p>A Result can represent success or failure.</p><p>An Api describes the capabilities available to a computation.</p><p>A DomainModel translates transport objects into domain concepts.</p><p>Yet none of these objects answers a much more interesting question:</p><blockquote><strong><em>How do we describe a computation without executing it?</em></strong></blockquote><p>Suppose we want to express the following workflow:</p><pre>Fetch User → Create Post → Upload Attachment → Notify User</pre><p>This is more than a sequence of simple function calls. Each step depends on the successful completion of the previous one. Any failure should immediately terminate the workflow; every step requires access to the same networking environment; and yet, nothing should actually execute until we’re ready.</p><p>What we need is an object capable of <strong>describing</strong> this computation before it runs. That object is an effect.</p><h3>Effects Describe Work</h3><p>An effect is simply a value that represents work yet to be performed.</p><p>Instead of immediately executing a network request, we construct a description of the computation. You might first reach for the simplest possible shape: a computation is just a function from an environment C to a result R.</p><pre>// C represents the environment and R represents the result<br>Computation&lt;C, R&gt; ≈ (C) -&gt; R</pre><p>That’s the right intuition, but a bare function type gives us nowhere to hang behaviour — no way to attach compose, no way to attach switchContext. So we wrap it in a class instead, and that class, not the function type above, is what we actually build on for the rest of this piece:</p><pre>class Computation&lt;C, R&gt;(<br>    private val f: suspend (C) -&gt; R<br>) {<br>    suspend fun runInContext(context: C): R =<br>        f(context)<br>}</pre><blockquote><em>Computation&lt;Get, User&gt; means a computation that requires a </em><em>Get and eventually produces a </em><em>User. The type parameter has been simplified here — normally we&#39;d want a </em><em>Result&lt;User, NetworkError&gt;, not just </em><em>User.</em></blockquote><blockquote><em>An effect separates two ideas:</em></blockquote><blockquote>1. Constructing the computation is one step<br>2. Executing the computation is another.</blockquote><p>This separation gives us something remarkably powerful. Because a computation is now just another value, it can be transformed, combined, passed around, and reasoned about before any network request is ever made.</p><h3>Composing Effects</h3><p>Once computations become values, they can be composed just like any other data structure. Suppose one computation produces a User. A second computation requires that User in order to get the UserHistory. Instead of manually unpacking values and checking for failures, we simply compose the two computations together.</p><p>Conceptually, the pipeline looks like this:</p><pre>// we use a simplified representation of a computation.<br>(Get) -&gt; User // Given computation_1<br>(User) -&gt; (Get) -&gt; UserHistory // computation_2<br>(Get) -&gt; UserHistory // producing computation_3</pre><p>A function that composes computation_1 and computation_2 can be written as:</p><pre>fun compose(<br>    first: (Get) -&gt; User,<br>    next: (User) -&gt; (Get) -&gt; UserHistory<br>): (Get) -&gt; UserHistory =<br>    { get: Get -&gt;<br>        next(first(get))(get)<br>    }</pre><p>Adapting the compose function for our class, which is generic, we have:</p><pre>class Computation&lt;C, R&gt;(<br>    private val f: suspend (C) -&gt; R<br>) {<br>	fun &lt;R2&gt; compose(<br>		f: (R) -&gt; Computation&lt;C,R2&gt;<br>	): Computation&lt;C,R2&gt; =<br>		Computation { c -&gt; f(this.runInContext(c)).runInContext(c) }<br>	<br>    suspend fun runInContext(context: C): R =<br>        f(context)<br>}</pre><p>compose is this codebase&#39;s name for what functional programmers usually call flatMap or monadic bind — same operation, domain-specific name. We&#39;ll stick with compose consistently from here on, since that&#39;s the name the rest of this piece, and the code built on top of it, actually uses.</p><p>Now suppose one computation produces a User. A second computation requires that User in order to create a post. We would want to compose both computations, but this yields a new challenge: we change the environment from Get to Post, unlike the first example where the environment is unchanged.</p><p>Visualising the pipeline:</p><pre>// we use a simplified representation of a computation.<br>(Get) -&gt; User // Given computation_1<br>(User) -&gt; (Post) -&gt; Status // computation_2<br>(Post) -&gt; Status // producing computation_3</pre><p>Here is the candid truth about changing the environment: because the context is an input to your computation rather than an output, the mapping happens backwards. If we want to create a new computation that accepts a completely different context like Post, we have to provide a function that translates Post back into the Get our original computation actually needs.</p><pre>fun switchContextAndCompose(<br>    transform: (Post) -&gt; Get,<br>    first: (Get) -&gt; User,<br>    next: (User) -&gt; (Post) -&gt; Status<br>): (Post) -&gt; Status =<br>    { post: Post -&gt;<br>        next(first(transform(post)))(post)<br>    }</pre><p>It’s worth separating this into two ideas rather than one, because the “switch” half and the “compose” half are independently useful. The switch half — reindexing the environment without touching the result — is the smaller, more primitive operation:</p><pre>class Computation&lt;C, R&gt;(<br>    private val f: suspend (C) -&gt; R<br>) {<br>    fun &lt;R2&gt; compose(<br>	f: (R) -&gt; Computation&lt;C,R2&gt;<br>    ): Computation&lt;C,R2&gt; =<br>	Computation { c -&gt; f(this.runInContext(c)).runInContext(c) }<br><br>    // Transforms the Context (Backwards / Contravariant)<br>    fun &lt;C2&gt; switchContext(transform: (C2) -&gt; C): Computation&lt;C2, R&gt; =<br>        Computation { c2 -&gt; this.runInContext(transform(c2)) }<br><br>    // The fused convenience version - switch, then compose, in one call<br>    fun &lt;C2, R2&gt; switchContextAndCompose(<br>        transform: (C2) -&gt; C,<br>        f: (R) -&gt; Computation&lt;C2, R2&gt;<br>    ): Computation&lt;C2, R2&gt; =<br>        switchContext(transform).compose(f)<br><br>    suspend fun runInContext(context: C): R =<br>        f(context)<br>}</pre><p>switchContextAndCompose isn&#39;t hand-written separately from switchContext and compose — it&#39;s defined <em>in terms of</em> them, and the two forms are provably interchangeable: composing switchContext(transform) with compose(f) produces the exact same result, for any input, as calling switchContextAndCompose(transform, f) directly. Keeping switchContext around as its own method, rather than only ever using the fused version, means a caller who only needs to reindex the environment — without immediately composing anything afterward — has a way to say exactly that, and nothing more.</p><p>Each stage consumes the successful result of the previous stage; failures automatically propagate; the networking environment continues to flow through the pipeline.</p><p>At this level, we haven’t said anything about Retrofit, Ktor, HTTP clients, retries, logging, or serialization.</p><p>The effect only answers one question:</p><blockquote><strong><em>What should happen?</em></strong></blockquote><p>It deliberately says nothing about <strong>how</strong> it happens.</p><h3>Separating Effects from Execution</h3><p>This distinction eventually led to splitting the architecture into two independent abstractions.</p><p>The first is Computation. Its responsibility is to describe computations.</p><p>It knows how to:</p><ul><li>compose computations (compose)</li><li>reindex the environment a computation runs against (switchContext)</li><li>propagate failures</li><li>thread the networking environment through the pipeline</li></ul><p>It does <strong>not</strong> know how to perform a network request; that responsibility belongs elsewhere.</p><p>The second abstraction is NetworkExecutor. Its responsibility is to execute computations.</p><p>It decides:</p><ul><li>how requests are dispatched,</li><li>which HTTP client is used,</li><li>whether retries should occur,</li><li>how errors are classified,</li><li>how metrics and logging are collected,</li><li>and how transport-specific exceptions are translated into domain-independent errors.</li></ul><p>The effect describes the program.</p><p>The executor interprets it.</p><p>Mathematically, you can think of the relationship like this:</p><pre>                  Computation<br>              (Description of work)<br>                       │<br>                interpreted by<br>                       │<br>                NetworkExecutor<br>                       │<br>        ┌──────────────┴──────────────┐<br>        │                             │<br> RetrofitExecutor              KtorExecutor</pre><p>The beauty of this separation is that the description never changes.</p><p>Whether the computation is executed using Retrofit, Ktor, a mock implementation, or an in-memory fake for unit tests, the effect remains exactly the same.</p><p>Only the interpreter changes.</p><h3>From Effects to Programs</h3><p>At this point, we’ve arrived at a very different understanding of what a repository can be. It is no longer an object that hides a networking library; it is no longer a collection of CRUD methods.</p><p>Instead, it becomes a program — a composable description of work that can be folded or reduced, transformed, combined, and laid out as a pipeline.</p><h3>Capabilities Instead of Services</h3><p>Traditional Android architectures typically begin by defining transport scopes named after data domains — such as UserService, PostService, or WeatherService. These traditional definitions explicitly couple your business logic to who owns the endpoint or how the backend team structured their microservices.</p><p>A functional, effect-driven architecture turns this inside out. Instead of modelling <em>ownership scopes</em>, we model <em>behavioural capabilities</em>. The execution framework doesn’t care which service an endpoint belongs to; it only cares about the underlying semantic properties of the HTTP verb being used.</p><p>We enforce these properties at the type level using marker interfaces, and — as noted above — every one of them extends Api consistently, since that&#39;s what lets a single CapabilityRegistry hold all of them behind one type-safe map:</p><pre>sealed interface Api<br><br>interface Get : Api {<br>    suspend fun getUser(id: String): Users.User<br>    suspend fun getPosts(): List&lt;Posts.Post&gt;<br>}<br><br>interface Put : Api {<br>    suspend fun updateUser(id: String, request: UserUpdateRequest): Users.User<br>}<br><br>interface Delete : Api {<br>    suspend fun deleteUser(id: String)<br>}<br><br>// Retrying a create can duplicate resources. Do not retry.<br>interface Post : Api {<br>    suspend fun createUser(request: UserCreateRequest): Users.User<br>    suspend fun createPost(request: PostCreateRequest): Posts.Post<br>}</pre><p>By splitting capabilities into Get, Post, Put, and Delete, our business logic pipelines depend strictly on behavioural traits.</p><p>To centralise these capabilities, we create a CapabilityRegistry class that acts as a service locator by providing a central object from which consumers can dynamically retrieve the service/capability they need by its type, rather than receiving each dependency directly through constructor injection.</p><pre>class CapabilityRegistry internal constructor(<br>    @PublishedApi internal val capabilities: Map&lt;KClass&lt;out Api&gt;, Api&gt;<br>) {<br><br>    inline fun &lt;reified V : Api&gt; get(): V =<br>        capabilities[V::class] as? V<br>            ?: error(&quot;No ${V::class.simpleName} capability registered for this session&quot;)<br><br>    class Builder {<br>        @PublishedApi internal val map = mutableMapOf&lt;KClass&lt;out Api&gt;, Api&gt;()<br>        inline fun &lt;reified V : Api&gt; register(instance: V): Builder {<br>            map[V::class] = instance<br>            return this<br>        }<br>        fun build(): CapabilityRegistry = CapabilityRegistry(map.toMap())<br>    }<br>}</pre><p>In the design of this class, we use the builder pattern to separate construction of the registry object from its usage. After construction, consumers get a snapshot rather than a registry that can arbitrarily change underneath them. So, we can increase the number of capabilities of a registry without affecting the portion of code that already uses an instance of this registry.</p><p>Things worth noting about the registry:</p><ol><li>It’s worth being precise about what kind of safety this buys us and what it doesn’t — a .get&lt;V&gt;() call against a registry missing that capability fails at runtime, not compile time. We come back to exactly this trade-off in Correctness by Construction.</li><li>The registry can contain both low-level transport capabilities like Get, Post, Delete and domain-oriented APIs: UserService, PostService, AuthService if you choose to support the model used by the backend</li></ol><h3>Transport Is Just an Interpreter</h3><p>A major advantage of isolating description from execution is that the pipeline written above remains completely unaware of how the network bytes are delivered. The business logic specifies <em>what</em> capabilities it requires, while the concrete implementation of the transport layer is treated merely as an interpreter.</p><p>The execution boundary is reduced to a plain suspend interface:</p><pre>interface NetworkExecutor {<br>    suspend fun &lt;DTO : DomainModel&lt;Domain&gt;, Domain&gt; execute(<br>        retryPolicy: RetryPolicy = RetryPolicy(),<br>        request: suspend () -&gt; DTO<br>    ): Result&lt;Domain, NetworkError&gt;<br>}</pre><p>This design allows you to easily switch between client implementations. Swapping Retrofit out for Ktor requires no modifications to your business logic pipelines or your view models. You simply swap out the concrete interpreter instance provided to the chain.</p><h4>The Retrofit Interpreter</h4><pre>import com.github.michaelbull.result.*<br>import kotlinx.coroutines.CancellationException<br>import kotlinx.coroutines.delay<br>import retrofit2.HttpException<br><br>class RetrofitExecutor : NetworkExecutor {<br>    override suspend fun &lt;DTO : DomainModel&lt;Domain&gt;, Domain&gt; execute(<br>        retryPolicy: RetryPolicy,<br>        request: suspend () -&gt; DTO<br>    ): Result&lt;Domain, NetworkError&gt; {<br>        var lastError: NetworkError? = null<br>        repeat(retryPolicy.maxRetries) { attempt -&gt;<br>            try {<br>                return Ok(request().toDomain())<br>            } catch (e: CancellationException) {<br>                throw e // Must rethrow to respect coroutine structured concurrency<br>            } catch (e: HttpException) {<br>                val classified = classify(e)<br>                if (classified is NetworkError.ServerError &amp;&amp; classified.code in retryPolicy.retryableHttpCodes) {<br>                    lastError = classified<br>                    delay(retryPolicy.delayFor(attempt))<br>                } else {<br>                    return Err(classified)<br>                }<br>            } catch (e: Exception) {<br>                return Err(NetworkError.Unexpected(e))<br>            }<br>        }<br>        return Err(lastError ?: NetworkError.Unexpected(IllegalStateException(&quot;Exhausted retries with no recorded error&quot;)))<br>    }<br>    private fun classify(e: HttpException): NetworkError = when (e.code()) {<br>        in 500..599 -&gt; NetworkError.ServerError(e.code(), e)<br>        in 400..499 -&gt; NetworkError.ClientError(e.code(), e)<br>        else -&gt; NetworkError.Unexpected(e)<br>    }<br>}</pre><h4>The Ktor Interpreter</h4><pre>import com.github.michaelbull.result.*<br>import io.ktor.client.plugins.*<br>import kotlinx.coroutines.CancellationException<br>import kotlinx.coroutines.delay<br><br>class KtorExecutor : NetworkExecutor {<br>    override suspend fun &lt;DTO : DomainModel&lt;Domain&gt;, Domain&gt; execute(<br>        retryPolicy: RetryPolicy,<br>        request: suspend () -&gt; DTO<br>    ): Result&lt;Domain, NetworkError&gt; {<br>        var lastError: NetworkError? = null<br>        repeat(retryPolicy.maxRetries) { attempt -&gt;<br>            try {<br>                return Ok(request().toDomain())<br>            } catch (e: CancellationException) {<br>                throw e<br>            } catch (e: ServerResponseException) {<br>                // Ktor only throws ServerResponseException for 5xx responses in the first<br>                // place, so there&#39;s no separate &quot;is this eligible&quot; check needed here -<br>                // catching this exception type already answers that question.<br>                val code = e.response.status.value<br>                val classified = NetworkError.ServerError(code, e)<br>                if (code in retryPolicy.retryableHttpCodes) {<br>                    lastError = classified<br>                    delay(retryPolicy.delayFor(attempt))<br>                } else {<br>                    return Err(classified)<br>                }<br>            } catch (e: ClientRequestException) {<br>                return Err(NetworkError.ClientError(e.response.status.value, e))<br>            } catch (e: Exception) {<br>                return Err(NetworkError.Unexpected(e))<br>            }<br>        }<br>        return Err(lastError ?: NetworkError.Unexpected(IllegalStateException(&quot;Exhausted retries with no recorded error&quot;)))<br>    }<br>}</pre><pre>import kotlin.random.Random<br><br>data class RetryPolicy(<br>    val maxRetries: Int = 3,<br>    val retryableHttpCodes: Set&lt;Int&gt; = setOf(502, 503, 504),<br>    val baseDelayMs: Long = 250L,<br>    val maxDelayMs: Long = 4_000L,<br>    val jitterMs: Long = 100L<br>) {<br>    /** Jittered exponential backoff, capped at [maxDelayMs] so retries can&#39;t stall forever. */<br>    fun delayFor(attempt: Int): Long {<br>        val exponential = baseDelayMs * (attempt + 1)<br>        val capped = exponential.coerceAtMost(maxDelayMs)<br>        return capped + Random.nextLong(0, jitterMs + 1)<br>    }<br>}</pre><h3>A Real Example: OpenWeather</h3><p>Everything so far has described Computation in the abstract. Before it&#39;s useful, something has to bridge it to NetworkExecutor — nothing yet has shown how a leaf computation actually turns into a real network call. That bridge is a small extension function on NetworkExecutor:</p><pre>fun &lt;C, DTO : DomainModel&lt;Domain&gt;, Domain&gt; NetworkExecutor.effect(<br>    retryPolicy: RetryPolicy = RetryPolicy(),<br>    request: suspend (C) -&gt; DTO<br>): Computation&lt;C, Result&lt;Domain, NetworkError&gt;&gt; =<br>    Computation { c -&gt; this.execute(retryPolicy) { request(c) } }</pre><p>Given an executor and a suspend function from the environment to a DTO, effect produces exactly the kind of Computation the rest of this piece has been building toward — one whose result is already a Result&lt;Domain, NetworkError&gt;, with retries and error classification handled by whichever NetworkExecutor you pass in.</p><p>With that in place, consider a sequential pipeline where we must first resolve a city’s text name into geographic coordinates before fetching its current weather conditions. Both steps are reads, so both live under the same Get capability:</p><pre>interface Get : Api {<br>    suspend fun geocode(city: String): GeoResponseDto<br>    suspend fun currentWeather(lat: Double, lon: Double): WeatherResponseDto<br>}</pre><pre>data class Coordinates(val lat: Double, val lon: Double)<br>data class GeoResponseDto(val lat: Double, val lon: Double) : DomainModel&lt;Coordinates&gt; {<br>    override fun toDomain() = Coordinates(lat, lon)<br>}<br>data class CurrentWeather(val tempCelsius: Double, val description: String)<br>data class WeatherResponseDto(val tempKelvin: Double, val description: String) : DomainModel&lt;CurrentWeather&gt; {<br>    override fun toDomain() = CurrentWeather(tempKelvin - 273.15, description)<br>}</pre><h3>Composing Network Requests</h3><p>Because an effect is modelled as a plain immutable value, assembling multiple network requests into an interdependent pipeline becomes highly predictable. Instead of managing complex control flow, developers use combinator functions to transform or chain responses. compose already gets us same-context chaining, but its callback receives the raw R — if R is a Result, compose has no idea it&#39;s carrying a Result, and won&#39;t stop calling the next step just because the previous one failed. To get that specifically, we build a small, Result-aware layer on top of compose:</p><pre>fun &lt;C, R1, R2, E&gt; Computation&lt;C, Result&lt;R1, E&gt;&gt;.flatMapResult(<br>    transform: (R1) -&gt; Computation&lt;C, Result&lt;R2, E&gt;&gt;<br>): Computation&lt;C, Result&lt;R2, E&gt;&gt; =<br>    this.compose { result: Result&lt;R1, E&gt; -&gt;<br>        Computation { c: C -&gt;<br>            // Result&#39;s own flatMap unwraps on success and short-circuits on<br>            // failure, without ever invoking `transform` on the error path.<br>            result.flatMap { r1: R1 -&gt; transform(r1).runInContext(c) }<br>        }<br>    }</pre><pre>fun &lt;C, R1, R2, E&gt; Computation&lt;C, Result&lt;R1, E&gt;&gt;.mapResult(<br>    transform: (R1) -&gt; R2<br>): Computation&lt;C, Result&lt;R2, E&gt;&gt; =<br>    this.compose { result -&gt; Computation { result.map(transform) } }</pre><pre>fun &lt;C1, C2, R1, R2, E&gt; Computation&lt;C1, Result&lt;R1, E&gt;&gt;.switchContextAndFlatMapResult(<br>    extractContext: (C2) -&gt; C1,<br>    transform: (R1) -&gt; Computation&lt;C2, Result&lt;R2, E&gt;&gt;<br>): Computation&lt;C2, Result&lt;R2, E&gt;&gt; =<br>    this.switchContext(extractContext).flatMapResult(transform)</pre><p>The geocode-then-weather pipeline is a direct application of flatMapResult:</p><pre>fun weatherFor(city: String, executor: NetworkExecutor): Computation&lt;Get, Result&lt;CurrentWeather, NetworkError&gt;&gt; =<br>    executor.effect&lt;Get, GeoResponseDto, Coordinates&gt; { get -&gt; get.geocode(city) }<br>        .flatMapResult { coordinates -&gt;<br>            executor.effect&lt;Get, WeatherResponseDto, CurrentWeather&gt; { get -&gt;<br>                get.currentWeather(coordinates.lat, coordinates.lon)<br>            }<br>        }</pre><p>And running it end to end, through the actual CapabilityRegistry rather than a hand-wired capability instance:</p><pre>val registry = CapabilityRegistry.Builder()<br>    .register&lt;Get&gt;(OpenWeatherApi(httpClient))<br>    .build()</pre><pre>val weather: Result&lt;CurrentWeather, NetworkError&gt; =<br>    weatherFor(&quot;Lagos&quot;, RetrofitExecutor()).runInContext(registry.get&lt;Get&gt;())</pre><p>Look closely at what is happening here. Neither .flatMapResult() nor .effect() executes anything eagerly; each call yields a brand-new Computation value that wraps the updated step description. If geocoding fails, the error track instantly short-circuits the rest of the execution — the closure that would call currentWeather is never invoked at all, not merely &quot;unlikely to run.&quot; That&#39;s not a claim about typical behaviour; it falls directly out of Result.flatMap&#39;s definition, which returns immediately on Err without calling its transform.</p><p>If this pattern of chaining operations feels familiar, it is because <strong>we have arrived at a Monad</strong>. We did not start with category theory or pure mathematical blueprints; we arrived here entirely out of a practical engineering need to safely compose interdependent, error-prone asynchronous tasks.</p><p>The monadic nature of Computation hides the messy infrastructure of Android development behind a clean interface:</p><ul><li><strong>The Context:</strong> It carries the data state, capability boundaries, and error boundaries along the railway track.</li><li><strong>The Map Functor:</strong> .mapResult() transforms the success value in place if the pipeline is succeeding, and passes failures through unchanged.</li><li><strong>The FlatMap/Bind Monad:</strong> .flatMapResult(), and its capability-switching counterpart .switchContextAndFlatMapResult(), each accept a function that takes an unwrapped domain value and produces the next computation — short-circuiting automatically the moment any step in the chain fails.</li></ul><h3>Correctness by Construction</h3><p>Two different kinds of correctness are at play in this architecture, and it’s worth being precise about which parts of the design actually deliver which kind.</p><p><strong>Compile-time.</strong> A Computation&lt;Get, Result&lt;Users.User, NetworkError&gt;&gt; cannot be run against anything that isn&#39;t a Get. The type of every computation is a checked claim about what capability it needs — hand it a Post and the program is rejected before it ever runs. Crossing from one capability to another is never silent or implicit; it happens through switchContext, visibly, wherever it occurs in the code. That&#39;s the actual return on modelling Get/Post/Put/Delete as marker interfaces rather than as fields on some settings object: not runtime validation, but a program that is simply ill-typed if it tries to use a capability it never declared.</p><p><strong>Runtime, but disciplined.</strong> Whether a particular request succeeds or fails can’t be known until it actually runs — no type signature is going to predict a 500 in advance. What the architecture buys instead is a guarantee about <em>propagation</em>. Once flatMapResult composes two steps, a failure in the first is provably incapable of reaching the second: not &quot;the second step will probably be skipped,&quot; but literally no code path in flatMapResult&#39;s own definition ever invokes the next closure once the first result is an Err. That&#39;s a stronger property than &quot;we remembered to check is Err at every call site&quot; — it&#39;s checkable directly from the combinator&#39;s definition, once, rather than from convention at every place it&#39;s used.</p><p><strong>Where this stops being compile-time.</strong> CapabilityRegistry.get&lt;V&gt;() is a runtime lookup. Build a registry that never registered Delete, and something downstream calling .get&lt;Delete&gt;() gets an error(...) at runtime, not a compiler error. This is a deliberate, contained trade-off rather than an oversight — the registry is a single, known point where incomplete configuration becomes a runtime failure, rather than that risk being scattered across arbitrary call sites the way a raw service locator usually allows. It is also, honestly, the one place in this architecture where &quot;correctness by construction&quot; doesn&#39;t fully hold. Tightening it further — a registry that only compiles if every capability the workflow&#39;s Computation types require was actually registered — is possible, using structurally-typed or phantom-typed registries, but adds real complexity, and isn&#39;t a change worth making until a project actually needs it.</p><h3>Where This Leaves the Repository Pattern</h3><p>We started by asking what a repository is actually for, and the traditional answer — “a place that hides where data comes from” — turned out to explain very little about the problems repositories tend to create in practice: orchestration logic bleeding into ViewModels, retry logic copy-pasted across every use case, and no real way to compose two network calls without writing bespoke glue code each time.</p><p>The repository doesn’t disappear in this architecture so much as it gets split into pieces that were always doing different jobs. Computation describes what should happen. NetworkExecutor decides how it happens. CapabilityRegistry decides who gets to make it happen. None of the three needs to know how the other two are implemented, and none of them individually resembles a repository — which is the point. What used to be a UserRepository with six unrelated methods on it becomes a handful of small, independently testable Computation values, composed together at the point a feature actually needs them, rather than pre-bundled into a class organised around a database table or a REST resource that has nothing to do with how the app actually uses it.</p><p>The cost is real, and worth naming plainly: this is more machinery than a repository interface and an implementation. For a small app with three network calls that never compose, it’s almost certainly overkill. It earns its complexity specifically where the original problem lived — workflows that chain several requests, need consistent retry and error handling across all of them, and where “does this actually short-circuit on failure” used to be true only because someone remembered to write if (result is Err) return at every step. Here, it&#39;s true because the composition operators don&#39;t have another code path to take.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3e9310687a8b" width="1" height="1" alt=""><hr><p><a href="https://proandroiddev.com/rethinking-networking-in-android-turning-android-repositories-into-composable-effects-3e9310687a8b">Rethinking Networking in Android (Turning Android Repositories into Composable Effects)</a> was originally published in <a href="https://proandroiddev.com/">ProAndroidDev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Search Dialog Component — A compose implementation]]></title>
            <link>https://proandroiddev.com/search-dialog-component-a-compose-implementation-2b198fdb13a7?source=rss-20e877f606ea------2</link>
            <guid isPermaLink="false">https://medium.com/p/2b198fdb13a7</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[jetpack-compose]]></category>
            <category><![CDATA[ui]]></category>
            <category><![CDATA[ux-design]]></category>
            <dc:creator><![CDATA[Davies Adedayo AbdulGafar]]></dc:creator>
            <pubDate>Sat, 26 Jul 2025 13:06:28 GMT</pubDate>
            <atom:updated>2025-08-31T21:48:51.082Z</atom:updated>
            <content:encoded><![CDATA[<h3>Search Dialog Component — A compose implementation</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rvIx5ibRCmZscnIcTknhxQ.png" /></figure><p>I’ve always wanted to build a utilitarian component in Jetpack Compose — something that’s not just shiny or clever, but actually useful. That opportunity came when I ran into a painfully common problem while filling out a form.</p><p>Let me paint the picture: the form asks for your country, and you get a dropdown menu with over 300 countries to scroll through. You click the menu, start scrolling, and keep scrolling until you find your country. It’s tedious, especially on mobile. It would’ve been a much smoother experience if I could just search the list — not necessarily by typing the exact word — and get close matches instead of staring down the full list of countries.</p><p>This article walks you through how I approached this problem by implementing a custom <strong>search dialog component</strong>, focusing on performance, simplicity, and no external dependencies.</p><h4>Feature Highlights</h4><p>Here’s what sets this component apart:</p><ol><li><strong>No regex, no database, no third-party search libraries.</strong><br> It uses a smart indexing algorithm — the <strong>suffix array</strong> — to handle fast, in-memory search.</li><li><strong>Text highlighting.</strong><br> Matching parts of a result are highlighted, giving visual feedback on what exactly matched.</li><li><strong>Minimal UI.</strong><br> Simple, clean, and flexible. No bells and whistles.</li><li><strong>Debounced search.</strong><br> Prevents expensive operations on every keystroke. Efficient by design.</li></ol><h4>Suffix Array and Its Limitations</h4><p>Now, a quick note on how the search works. Suffix array is a heavy duty prefix search data structure that can find a prefix macth in O(log n) time, but the major bottle neck operation is its construction. The standard suffix array indexes all suffixes of a <strong>single string</strong>, “Hello world” is a trivial example. A non trivial example is indexing the entire text in this article making operations like KWIC (key word in context) possible.</p><p>The website <a href="https://algs4.cs.princeton.edu/code/edu/princeton/cs/algs4/SuffixArrayX.java.html">Algorithms 4th Edition</a> from Princeton University hosts an implementation of a suffix array with a decently fast construction time called SuffxArrayX. But out of the box, it only supports a single continuous string. If we were to use that as-is, the client code would have to merge all strings into one giant string, with some delimiter to mark where one ends and the next begins. Not ideal.</p><p>So instead, I generalised that implementation to work with <strong>a list of strings</strong>, giving us the GSuffArray. You can check out the implementation here: <a href="https://gist.github.com/SahDavies/0b49bde44f4606f009a44a350733bfd5">GSuffArray</a>.</p><h4>Overview</h4><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FHG6vjQ-77FI%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fshorts%2FHG6vjQ-77FI%3Ffeature%3Dshare&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FHG6vjQ-77FI%2Fhq2.jpg&amp;type=text%2Fhtml&amp;schema=youtube" width="640" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/1a48fe2753deb058b55bfbaa2103e0ec/href">https://medium.com/media/1a48fe2753deb058b55bfbaa2103e0ec/href</a></iframe><p>The component is designed to behave like a searchable dropdown — click to open a dialog, search through suggestions, and select a result.</p><p>The SearchDialog UI component consists of two main view transition:</p><ul><li><strong>View</strong>: Displays a clickable surface showing the selected item or placeholder text</li><li><strong>Search</strong>: Opens a dialog with a search field and filtered suggestions</li></ul><p>With the following state transition.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c4e508af09347d7a492b4def4ab506d4/href">https://medium.com/media/c4e508af09347d7a492b4def4ab506d4/href</a></iframe><ul><li>The view is a stateless composable implemented using a clickable surface composable that accepts a text composable as its content.</li><li>The search is stateless composable implemented using the basic dialog composable whose content is a basic text field and a LazyList layout to hold the suggestions.</li></ul><p>Below is a skeletal structure of the view and search state implementation</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8d39d896c73fdf9182dc348913047244/href">https://medium.com/media/8d39d896c73fdf9182dc348913047244/href</a></iframe><p>The function signature for both view and search explicitly informs their roles — View State only displays text, Search State is the interactive component.</p><p>Next we define parent composable that orchestrates the transition between both views. To keep things clean and follow the Compose philosophy, we define state holder class for composables instead of making the composables responsible for managing their state.</p><p>The following properties are what define the search dialog state holder class:</p><ol><li>query — a mutable state of the search term</li><li>foundMatch - a boolean used by the text field to show error state</li><li>gsa (generalised suffix array) — An abstraction that represents a sorted suffix of many strings not just a single string.</li><li>suggestions — a mutable state flow of a list of annotated strings. These strings are highlighted to indicate the searched characters.</li><li>queryFow - a mutable state flow of the search term for the purpose of debouncing.</li><li>items — a list of strings that would be indexed by gsa</li></ol><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/295d137105da606ab29941de965d30f3/href">https://medium.com/media/295d137105da606ab29941de965d30f3/href</a></iframe><p>The code for the parent composable that orchestrates the transitions is given below, together with the following events that triggers state changes.</p><ul><li>onClick() - The Search composable is conditionally called when the user clicks the on the ViewState composable</li><li>onQueryChange() - This is used to update the value of query state and query flow.</li><li>onSelectSuggestion() - It communicates the users choice by calling onSelectItem(), updates both query State and query flow then closes the dialog by calling searchDialogState.updateViewState()</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/05f56105b5e3d15be977a7dc6eeb094a/href">https://medium.com/media/05f56105b5e3d15be977a7dc6eeb094a/href</a></iframe><p>We currently have not implemented a way to update searchDialogState.suggestions whenever the query changes. Before doing that, there are a few things to consider:</p><ol><li>For each keystroke, we wouldn’t want to immediately engage the findMatch() function of the search dialog state as it is a fairly expensive operation. We should only engage the function after a set time interval (debounce).</li><li>Since the findMatch() can be a fairly expensive operation depending on the number of keystrokes entered by the user, we don&#39;t want it to run on the main thread.</li></ol><p>Inside the SearchDialog composable we make a call to LaunchedEffect and implement the search suggestion update in its block. Central to this implementation is the searchDialogState.queryFlow property. It serves as a key to LaunchedEffect and we use it as a computational context to implement debounce and other intermediate operations.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fd02da7b89eb1527d86cfe610d7db692/href">https://medium.com/media/fd02da7b89eb1527d86cfe610d7db692/href</a></iframe><p>The mapLatest block is responsible for transforming the user query into a list of matching suggestions with the help of the following functions:</p><ul><li>highlight() — returns an annotated string with highlight</li><li>searchDialogState.findMatchingIndex() —returns Map&lt;Int, List&lt;Int&gt;&gt; used by the highlight function</li></ul><p>The key of the map represents the index of the matching string found in the list of items, the value represents the start positions of the query character in this matching string.</p><p>Let’s say the query is &quot;iss&quot; and we have the list [&quot;Mississippi&quot;, &quot;Kisses&quot;]. Both contain &quot;iss&quot;, the resulting map for the matches are:</p><pre>mapOf(0 to listOf(1, 4), 1 to listOf(1))</pre><p>This information is used by the highlight function to generate an annotated string.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a20f8777dfd04477bb97e212ce1d1d8e/href">https://medium.com/media/a20f8777dfd04477bb97e212ce1d1d8e/href</a></iframe><h4>Example Usage</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/109d48c2b96cc7e70f49ccace76cb6b5/href">https://medium.com/media/109d48c2b96cc7e70f49ccace76cb6b5/href</a></iframe><p>This component was built out of necessity — to fix an everyday annoyance — and it turned into something flexible and powerful. With a few Compose APIs and a solid algorithm like the suffix array, you can make simple things better.</p><p>If you’re dealing with searchable lists, especially in forms or filters, give this approach a try. You won’t need a database, a search engine, or even regular expressions. Just a well-structured in-memory index, a little debounce logic, and some UI glue.</p><p>Here’s a link to the <a href="https://github.com/SahDavies/Search-Dialog.git">full implementation</a>. That’s all for now!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2b198fdb13a7" width="1" height="1" alt=""><hr><p><a href="https://proandroiddev.com/search-dialog-component-a-compose-implementation-2b198fdb13a7">Search Dialog Component — A compose implementation</a> was originally published in <a href="https://proandroiddev.com/">ProAndroidDev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Reactive State Management in Compose — MVI Architecture]]></title>
            <link>https://proandroiddev.com/reactive-state-management-in-compose-mvi-architecture-71546c9f1b52?source=rss-20e877f606ea------2</link>
            <guid isPermaLink="false">https://medium.com/p/71546c9f1b52</guid>
            <category><![CDATA[androiddev]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[mvi]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[android-app-development]]></category>
            <dc:creator><![CDATA[Davies Adedayo AbdulGafar]]></dc:creator>
            <pubDate>Mon, 21 Apr 2025 20:54:33 GMT</pubDate>
            <atom:updated>2025-04-21T20:54:33.469Z</atom:updated>
            <content:encoded><![CDATA[<h3>Reactive State Management in Compose — MVI Architecture</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bRox84HEmFZ9h4-6CoSm5Q.png" /><figcaption>Image credit <a href="https://www.figma.com/@sardor23">Sardor A</a> on <a href="https://www.figma.com/community/file/1327271715643161866">Figma</a></figcaption></figure><p>The MVI (Model-View-Intent) architecture offers a well-structured approach for scalable, robust, and testable ui state management in Android applications. It emphasises clean code and a clear separation of concerns by dividing the application into three main components — Model, View, and Intent — together, they form a loop: Intent -&gt; ViewModel -&gt; Model -&gt; View defining a unidirectional data flow. The distinct roles provided by this architecture pattern contribute to easier understanding, and maintenance of ui state. At its core, MVI isn&#39;t just an architectural pattern-it&#39;s a fundamentally <strong>reactive</strong> system designed to respond fluidly to changes. This reactivity is one of its defining characteristics and greatest strengths.</p><ul><li><strong>Unidirectional data flow:</strong> means data flows in a single direction — from the Model to the View and back as Intents. This ensures clarity, predictability, and ease of maintenance in the architecture.</li><li><strong>Separation of concerns:</strong> means distinct roles for Model, View, and Intent components. The Model manages the state, the View handles UI rendering, and the Intent captures and communicates user actions.</li><li><strong>Immutability:</strong> ensures that the Model’s state remains unchanged once set. This guarantees predictability, eliminates unexpected side effects, and promotes a stable and reliable application state.</li><li><strong>Reactive</strong>: The ui automatically updates when the state changes</li></ul><p>The architecture breaks down into three harmonious components that work together in a reactive flow:</p><ul><li>The <strong>Model</strong> serves as the single source of truth — a snapshot of your application’s state at any given moment. When this state changes, it triggers a cascade of reactive updates throughout the system. The UI automatically updates when the state changes, highlighting this core reactive principle.</li><li>The <strong>View</strong> reactively renders what the user sees based on the current model state. It subscribes to state changes and automatically transforms to reflect them without any imperative update calls. This reactive rendering is what makes MVI so powerful-the view is always in sync with the state.</li><li>The <strong>Intent</strong> completes the reactive circuit, capturing user interactions and feeding them back into the system to create new states. This creates a continuous feedback loop: user actions trigger intents, intents produce new states, and new states trigger UI updates.</li></ul><p>When we talk about MVI being reactive, we mean that the entire system is built around responding to changes automatically. The UI doesn’t need to be manually updated when data changes-instead, it automatically reflects the current state. This reactivity creates a dynamic, responsive application that feels alive to users.</p><p>In native android development, the bulk of the MVI implementation is placed in a ViewModel class. The following is a simple approach to implementing the MVI pattern:</p><ol><li>The UI state we intend to model would be implemented as an immutable Kotlin data class where its fields hold the states we would want to display in our view.</li><li>The StateFlow is the reactive glue that binds the entire architecture together. This observer object wraps the model and notifies the view of changes in order for it to reflect the new state. This reactive pipeline ensures that any state change automatically propagates to the UI.</li><li>Our intents for now can be implemented as a public function in the ViewModel. These function should have no return value to ensure that the view only receive state updates from the observer. Similar to the way objects are first class programming language construct and can be passed around through reference, likewise functions thanks to method reference. We take advantage of this to pass around intents to the ui node that uses it. We don&#39;t have to cook up a complicated class to model an intent which would require additional implementation of an intent handler.</li></ol><p>Below is a template of implementing an MVI pattern in a ViewModel.</p><pre>class ScreenViewModel() : ViewModel() {<br>  private val _uiState: MutableStateFlow&lt;MyModel&gt; = MutableStateFlow(MyModel(...)) // private observer object<br> <br>  val uiState: StateFlow&lt;MyModel&gt; = _uiState // observer object exposed as an immutable instance<br> <br>  fun doUpdateOnState(...) { ... } // public function serves as an intent<br>  fun doAnotherUpdate(...) { ... }<br>}<br><br>data class MyModel(...)</pre><p>New states are produced in the ViewModel and then consumed by the view observing the uiState. Notice how intents are passed on to composables screens as call backs that triggers a state change.</p><pre> @Composable<br> fun MyScreen(viewModel: ScreenViewModel) {<br>   val uiState: MyModel = viewModel.uiState.collectAsStateWithLifeCycle() // consumes the state produced in the viewModel<br>  <br>   MyScreenContent(<br>     uiState = uiState,<br>     doUpdate = viewModel::doUpdateOnState, // intent to do update<br>     doAnotherUpdate = viewModel::doAnotherUpdate // intent to do another update<br>   )<br> }</pre><p>This reactive pattern comes to life through Kotlin’s StateFlow:</p><pre>private val _uiState: MutableStateFlow&lt;MyModel&gt; = MutableStateFlow(MyModel(...))<br>val uiState: StateFlow&lt;MyModel&gt; = _uiState</pre><p>On the UI side, this reactivity is expressed through a collect operation consuming new states as they are produced from the viewModel.</p><pre>val uiState = viewModel.uiState.collectAsStateWithLifeCycle()</pre><p>This single line establishes a reactive connection that automatically refreshes the UI whenever the state changes. There’s no need for manual refresh calls or complex update logic-the system is inherently reactive.</p><h3>Case Study</h3><p>Let’s take a more practical approach and implement an MVI pattern to manage the state of a screen. Below is a screen that allows users to select from the given options an answer to the displayed question.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/419/0*uwa_-6EYNOhyNuNJ" /></figure><p>Image credit — <a href="https://github.com/android/compose-samples/tree/v2024.01.00/Jetsurvey">Compose samples Jetsurvey</a>. Click <a href="https://github.com/SahDavies/mvi-architecture-sample/">here</a> to view the full implementation</p><p>The screen consists of the following states:</p><ol><li>A question</li><li>A list of options</li><li>A question count</li><li>A selection indicator</li><li>Enable/disable button</li></ol><p>In addition, the screen provides input for the following user action:</p><ol><li>Get the next question</li><li>Get the previous question</li><li>Select an option</li><li>Close/end action These actions are used to communicate the user’s intents to the application.</li></ol><p>The model that holds the state for the screen can be implemented as such</p><pre>data class UiState(<br>  val questionCount: Int,<br>  val totalQuestion: Int,<br>  val question: Question,<br>  val userSelection: Option?<br>) {<br>  val hasNext: Boolean = questionCount &lt; totalQuestion<br>  val hasPrevious: Boolean = questionCount &gt; 1<br>}</pre><p>As mentioned earlier for simplicity, we describe the intents using public functions and these functions have no return value. We enumerate the functions we would be implementing in the ViewModel below.</p><pre>fun next() // loads next question<br>fun previous() // loads previous question<br>fun onOptionSelected(selection: Option) // activates indicator for selected item</pre><p>Each function when called in the view triggers a new state to be emitted for the view to consume, and with this our screen is predictable and testable since each user interaction produces a new immutable state that can be compared against during tests.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2eea13dac881cba96b157dfcd88e20d2/href">https://medium.com/media/2eea13dac881cba96b157dfcd88e20d2/href</a></iframe><p>Note: Not all screen component with state can be managed with MVI. Some are managed in a separate state holder class, some are internal state managed in the composable itself — take the progress indicator in the above screen for example. State not really dealing with business logic shouldn’t be managed using MVI.</p><h3>Beyond Basic Reactivity</h3><p>The case study above used a simple implementation of a model based on our screen requirement. There are quite a few ways to write a model implementation for MVI pattern — an implementation informed by screen requirement — take for example a screen with a loading and error state. Usually it is most simply achieved using sealed class hierarchy — all this being said, you have the choice of implementing your own model differently.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7d11ca7e122a8339a9028a7fedc5a554/href">https://medium.com/media/7d11ca7e122a8339a9028a7fedc5a554/href</a></iframe><p>The view consumes this new type a bit differently like so</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f1514d63193d232eebed377a2396f922/href">https://medium.com/media/f1514d63193d232eebed377a2396f922/href</a></iframe><p>It is important to note that this type of model is mutually exclusive — it guarantees that all three states cannot happen all at once but one at a time which helps prevent a common bug in UI state rendering.</p><h4>Rewriting an Intent Implemention</h4><p>The intent implementation can also be modified by adding a reducer/handler which is a public function in the viewmodel that then calls private implementation (helper functions) to perform an action using when expression to branch to corresponding action.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/53bf3898bc3f9d5c2f46d94fe5b124de/href">https://medium.com/media/53bf3898bc3f9d5c2f46d94fe5b124de/href</a></iframe><p>In order for this setup to work, we then define a sealed interface hierarchy corresponding to each action whose subclass properties are used to hold arguments that would then be passed on to these actions through the reducer/handler from the view.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/177b10fe87b7c5e52b35e28936ae4ad0/href">https://medium.com/media/177b10fe87b7c5e52b35e28936ae4ad0/href</a></iframe><p>Unlike our first implementation of an intent that requires us to pass the entire actions using method reference in the view, here we only need to pass the reducer/handler. Then the responsibility of deciding what action needs to be called is scoped to the caller.</p><p>Here is how it looks from the view</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/28a31fb47b83af07440ea78036e00e6f/href">https://medium.com/media/28a31fb47b83af07440ea78036e00e6f/href</a></iframe><p>HomeContent composable is now responsible for deciding which action to call by instantiating any of the following objects then calling onHomeAction with the instantiated object</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2e7652446713e4648b576e0fdc1ea0a8/href">https://medium.com/media/2e7652446713e4648b576e0fdc1ea0a8/href</a></iframe><p>See it in action below!</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/692ab042275515855135fd2bff2380bc/href">https://medium.com/media/692ab042275515855135fd2bff2380bc/href</a></iframe><p>Even with this added complexity, the core reactive principles remain intact. The reducer simply provides a more organized way to process intents and produce new states, while the reactive flow from state to UI remains unchanged.</p><p>This implementation makes it easy to build iteratively — whatever changes we need to make to our intents (whether adding new ones or removes existing ones) does not require rewrites in many places unlike our first implementations; we just register new actions in the handler, then instantiate a different object depending on our case when calling the handler.</p><p>To conclude this article, the most elegant aspect of MVI is how it creates a complete reactive circuit:</p><ol><li>The Model emits state</li><li>The View consumes state and renders UI</li><li>User interactions with the View generate Intents</li><li>Intents are processed to create new Models</li><li>The cycle continues reactively</li></ol><p>This unbroken reactive loop ensures that your application is always in sync with user actions and backend data. It’s not just about responding to changes-it’s about creating a system where changes flow naturally through a pre-defined reactive pathway.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=71546c9f1b52" width="1" height="1" alt=""><hr><p><a href="https://proandroiddev.com/reactive-state-management-in-compose-mvi-architecture-71546c9f1b52">Reactive State Management in Compose — MVI Architecture</a> was originally published in <a href="https://proandroiddev.com/">ProAndroidDev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Compose Navigation The Old Way]]></title>
            <link>https://proandroiddev.com/compose-navigation-the-old-way-af0f6add8743?source=rss-20e877f606ea------2</link>
            <guid isPermaLink="false">https://medium.com/p/af0f6add8743</guid>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[androiddev]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[compose-navigation]]></category>
            <category><![CDATA[builder-pattern]]></category>
            <dc:creator><![CDATA[Davies Adedayo AbdulGafar]]></dc:creator>
            <pubDate>Fri, 25 Oct 2024 16:42:20 GMT</pubDate>
            <atom:updated>2025-09-20T17:02:18.513Z</atom:updated>
            <content:encoded><![CDATA[<h4>A guide on how to define string routes safely</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/363/1*w5L8nyyx-1NVCDfmoZQnOg.png" /></figure><p>Traditionally, navigation in Compose relies on defining routes as strings, which opens up a lot of flexibility but also introduces potential risks if not handled carefully. In this guide, we’ll walk through how to safely define string routes, break down the structure of these routes, and address common problems encountered when using this method.</p><p>What this article is not — a guide on the new <a href="https://developer.android.com/guide/navigation/design/type-safety">type safe navigation</a></p><p>Click <a href="https://github.com/SahDavies/Compose-Destination.git"><strong>here</strong></a><strong> </strong>to view the complete Destinationsource code</p><h3>Understanding the Structure of Navigation Routes URI</h3><p>Compose navigation routes use a string pattern to define the paths between composables. These strings can contain both required and optional arguments, which dictate how data is passed to different screens in the app. Let’s break down the key components that make up a string route:</p><ol><li><strong>Route Name</strong>: The base of the string that represents the destination. It could be a simple string like &quot;home&quot;, &quot;profile&quot;, or &quot;details&quot;. This is the identifier of the composable you want to navigate to.<br> <br> Example:</li></ol><pre>val route = &quot;profile&quot;</pre><p>2. <strong>Required Arguments</strong>: These are values that must be provided when navigating to a specific route. A required argument follows the pattern /{argumentID}, where / acts as the delimiter separating multiple required arguments, and {} enclose the argument ID.</p><p>Example:</p><pre>val route = &quot;profile/{userId}&quot;</pre><p>Here, userID is a required argument. When navigating to the profile screen, you need to provide a value for userID.</p><p>3. <strong>Optional Arguments</strong>: These arguments are not mandatory for the route to function and are defined using query parameter syntax. An optional argument follows the pattern argumentID={argumentID}. The ? prefix marks the start of optional arguments, and &amp; is used as the delimiter to separate multiple optional arguments. Braces {} enclose the argument ID, which will be replaced with the actual argument when it is passed — the entire {argumentID} will be substituted by the provided argument (this same rule applies to required arguments as well).<br> <br> Example:</p><pre>val route = &quot;search?query={query}&quot;</pre><p>The query parameter is optional. If it’s not provided, the screen can still be displayed, but without the query term.</p><p>Together, a complete route might look something like this:</p><pre>val route = &quot;profile/{userId}?showDetails={showDetails}&amp;page={page}&quot;</pre><p>In this case, the userID is required, while showDetails and page are optional.</p><h4><strong>Case Study</strong></h4><p>Let’s take a case study of two screens:</p><p>1. A Form screen with three fields: Email, Phone number, social link<br>2. A profile screen that displays these information.</p><p>Let’s make the phone number and social link optional, the route for PROFILE_SCREEN accepts an email as a required argument, a phone number and social link as optional arguments. We follow the convention of using call backs to pass navController to screens using the signature<br>onNavigate: (route: String) -&gt; Unit</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/08ae1b8c206cd39859cd797c884eb3f4/href">https://medium.com/media/08ae1b8c206cd39859cd797c884eb3f4/href</a></iframe><p>The responsibility of generating the route is scoped to the screen that calls onNavigate</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b67def549e069829eadd025f75b4c7a5/href">https://medium.com/media/b67def549e069829eadd025f75b4c7a5/href</a></iframe><p>Since routes are defined as strings, navigating between screens requires that you embed the actual argument values within a route when needed, allowing for potential typos during route construction. This introduces a risk of your app crashing due to:</p><p>1. <strong>String Typing Errors</strong>: If you accidentally type profle/{userId} instead of profile/{userId}, it will break the navigation, as the navController object will have no record of that route. Such errors may not be immediately obvious.</p><p>2. <strong>Missing Arguments</strong>: If a required argument is omitted, the app will crash. For example, when navigating to profile/{userId}, if you do not provide the userID, navigation will fail.</p><p>3. <strong>Complexity with Multiple Arguments</strong>: When dealing with routes that require multiple arguments — especially if some are optional — it can become challenging to track what needs to be passed. The more complex the route becomes, the harder it is to ensure that the string is constructed correctly.</p><p>Handling routes in this manner within a production app that features many screens, each with its own set of arguments, can lead to a considerable amount of time spent debugging these routes. Clearly, there is a problem that requires an efficient solution.</p><h4>How can this problem be better managed?</h4><p>We need to define a route management model to mitigate errors. This model should reliably create routes with the correct patterns.</p><p><strong>Aim</strong>: The model should guarantee correctness, have a straight forward signature, and offer friendly usage.</p><p>The solution Ipresent is a data type that uses Joshua Bloch’s builder pattern, leveraging Kotlin’s DSL to provide a very descriptive usage</p><p><strong>The Destination Class API</strong></p><p>The data type we will call Destination holds the following properties and function</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4eea0a40ace2472ab3080e11ebe10726/href">https://medium.com/media/4eea0a40ace2472ab3080e11ebe10726/href</a></iframe><p><strong>Utility Class API</strong></p><p>The utility class is an inner class the holds utitlity function used to append actual arguments to routes</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/29d63b3f282f6837c0d08cdd84b59f19/href">https://medium.com/media/29d63b3f282f6837c0d08cdd84b59f19/href</a></iframe><p><strong>Builder Class API</strong></p><p>A nested builder class with utility functions to correctly create the route safely. The builder class is defined with the following functions</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/aaec2618cb6f87fc3f90094776c932e9/href">https://medium.com/media/aaec2618cb6f87fc3f90094776c932e9/href</a></iframe><h4>Sample Usage for Defining Routes and Navigating</h4><p>Using the APIs to define a navigation route then becomes a simple task.</p><ul><li>To create a destination instance that holds navigation information we call generate() passing a route id which is the base string identifier</li><li>To instantiate a destination with a required argument, generateRoute() accepts a lambda scoped to a receiver of type Builder. This lambda has access to withRequiredArgs() which is used to append required argument to the route under construction.</li><li>To instantiate a destination with optional arguments, we append them to the route under construction using withOptionalArgs().</li></ul><p><strong>Caution:</strong> withOptionalArgs()accepts a varargof NamedNavArgument objects and not String. Since compose navigation component requires that optional arguments provides an explicit list of NamedNavArgument.</p><p>Here is an example!</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7c0051ff3995c8d913a95dba9180da09/href">https://medium.com/media/7c0051ff3995c8d913a95dba9180da09/href</a></iframe><p>Once the destinations are defined, the navigation action looks like this:</p><pre>navController.navigate(FORM_ROUTE.navRoute())</pre><p>This navigates the user to the FORM_ROUTE, which has no arguments.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1c78eb5ae478724d076ed04019c3d59e/href">https://medium.com/media/1c78eb5ae478724d076ed04019c3d59e/href</a></iframe><p>This navigates the user to the PROFILE_ROUTE. Notice how we append argument values.</p><ul><li>An email is a required value, so it is appended via requiredArgs(&quot;sample@outlook.com&quot;).</li><li>phone_number and url are optional values, so we append them in one call using optionalArgs(&quot;01478219&quot;, &quot;http://www.mysociallink.com/profile&quot;)</li></ul><p>The optional arguments — phone_number and url can be omitted, and if not provided, the default values 0102030455 and null will be used respectively.</p><h4>Enforcing Type Safety For Argument</h4><p>Let’s add another layer of safety, where we define an extension function on NavControllerinstance whose purpose is to enforce type safety for arguments.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8cbacc4f7b00dd7cc94bed72ec1356b9/href">https://medium.com/media/8cbacc4f7b00dd7cc94bed72ec1356b9/href</a></iframe><p>Notice that optional argument have nullable types. The extension functions we define now serve as the entry point for our nav action. We do not need to directly navigate using PROIFILE_ROUTE, or FORM_ROUTE any longer.</p><p>Finally, adapting this solution for use in our sample case study<br>NavHost now looks like this</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/80548cc412e32d73fe01fbcf36d4567c/href">https://medium.com/media/80548cc412e32d73fe01fbcf36d4567c/href</a></iframe><p>FormScreen() responsible for navigating to profile now looks like this</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4a2e1f3527e226dbe3ce6fbbd6a6c3b6/href">https://medium.com/media/4a2e1f3527e226dbe3ce6fbbd6a6c3b6/href</a></iframe><p>You can find the Destination source code <a href="https://github.com/SahDavies/Compose-Destination.git"><strong>here</strong></a></p><h3><strong>(Edit) Exploiting the Destination Abstraction Even Further</strong></h3><p>We have dealt with enforcing type safety for route arguments, and the solution presented also guards against omission of required arguments. It would be useful to be able to retrieve arguments that has been passed to a route in a convenient manner too (emphasis on the convenient which means there are many inconvenient ways to retrieve them) but our solution does not cover this yet.</p><p>We already have a class that knows how to generate routes conveniently — Destination — now all we need to do is augment it. For each route, we define a class that augments the corresponding destination instance, where the class properties holds the route arguments. Taking our Profile route as an example, we create a data class called profile and populate the primary constructor with the route arguments.</p><pre>data class Profile(val email: String, val phoneNumber: Long?, val url: String?)</pre><p>Next, we define a secondary constructor that takes a `SavedStateHandle` as a parameter.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/09b4a14c2594ebea31266dc48bcb91df/href">https://medium.com/media/09b4a14c2594ebea31266dc48bcb91df/href</a></iframe><p>This allows us to instantiate the class in two different ways — using the primary constructor or using the secondary constructor. The wisdom behind this is that codes that need to send argument instantiates this class using the primary constructor while code that needs to retrieve argument instantiates this class using the secondary constructor. Notice that the companion object holds keys needed to retrieve arguments from the SavedStateHandle.</p><p>We then reference in the companion object a destination instance that corresponds to the profile route. This instance is what we are trying to augment.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1c4279de0ec1e87d91790b7d8db92db4/href">https://medium.com/media/1c4279de0ec1e87d91790b7d8db92db4/href</a></iframe><p>You might wonder why the instance is declared in a companion object. That’s because the surrounding class — the Profile data class — can be instantiated an unknown number of times, but its route representation stays the same for every instance. Therefore, we place this shared representation (the destination class) in the companion object.</p><p>We include in the Profile data class some additional properties and a method to complete its definition — route , namedNavArgument , navRoute().</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/febd118e437a298a171a71c307ce4f6c/href">https://medium.com/media/febd118e437a298a171a71c307ce4f6c/href</a></iframe><p>This solution is more robust, as it allows us to easily pass and retrieve arguments. Moreover, it can be extended to handle complex argument types — not just primitives — by using serialization within the navRoute() method. This way, a complex object can be serialized to a string before being passed to the destination instance.</p><p>Effectively managing navigation routes in Jetpack Compose can sometimes be an overwhelming task, especially for collaborative projects. Clearly, a structured approach is needed, and this guide offers one such method that leverages the Destination class and its builder to manage navigation routes. This approach ensures that routes are constructed consistently, helping to avoid runtime errors associated with string-based routes due to mismatched argument names or incorrect formatting. By implementing these strategies, you’ll enhance the overall quality of your application’s navigation architecture, leading to a smoother user experience and more maintainable code.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=af0f6add8743" width="1" height="1" alt=""><hr><p><a href="https://proandroiddev.com/compose-navigation-the-old-way-af0f6add8743">Compose Navigation The Old Way</a> was originally published in <a href="https://proandroiddev.com/">ProAndroidDev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>