<?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 Ahmed Atwa on Medium]]></title>
        <description><![CDATA[Stories by Ahmed Atwa on Medium]]></description>
        <link>https://medium.com/@a.atwaa94?source=rss-8a8e597dcef7------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*MFzTorFxEEC0ZFMV6poEaQ.png</url>
            <title>Stories by Ahmed Atwa on Medium</title>
            <link>https://medium.com/@a.atwaa94?source=rss-8a8e597dcef7------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 19 Nov 2026 21:41:00 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@a.atwaa94/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[A TCA-Inspired Architecture for Kotlin & Jetpack Compose — Why I Built Komposed]]></title>
            <link>https://medium.com/@a.atwaa94/a-tca-inspired-architecture-for-kotlin-jetpack-compose-why-i-built-komposed-c924610d9aa7?source=rss-8a8e597dcef7------2</link>
            <guid isPermaLink="false">https://medium.com/p/c924610d9aa7</guid>
            <category><![CDATA[mobile-development]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[jetpack-compose]]></category>
            <category><![CDATA[software-architecture]]></category>
            <dc:creator><![CDATA[Ahmed Atwa]]></dc:creator>
            <pubDate>Thu, 21 May 2026 20:29:35 GMT</pubDate>
            <atom:updated>2026-05-22T05:57:44.335Z</atom:updated>
            <content:encoded><![CDATA[<p><em>How a question from an iOS engineer friend exposed a gap in the Android ecosystem — and what I built to fill it.</em></p><h3>The Call That Started Everything</h3><p>It was a regular Tuesday evening when I got a message from an iOS engineer friend of mine. He had just been handed a new project — an Android app, built from scratch. No existing codebase, no inherited architecture, just a blank build.gradle.kts and a deadline.</p><p>His first question was not about Kotlin syntax or Compose APIs. It was this:</p><blockquote>“What’s the Android equivalent of TCA?”</blockquote><p>And I paused.</p><p>For context: <a href="https://github.com/pointfreeco/swift-composable-architecture">The Composable Architecture (TCA)</a> by Point-Free is, for many iOS engineers, the gold standard of scalable, testable, predictable app architecture. It gives you pure reducers, typed effects, composable features through lens-based state slicing, and a testing DSL that lets you assert the exact sequence of state changes and effects your app produces. It is opinionated in all the right ways.</p><p>My friend wasn’t asking for an architectural pattern. He was asking for a <em>framework</em> — something with the same structural guarantees, the same composability, the same first-class testability. Something you wire up and then spend your time writing app logic instead of reinventing plumbing.</p><p>The honest answer I gave him in that moment was: <em>I don’t know of one.</em></p><p>That answer bothered me enough that I spent the next week building one.</p><h3>What Already Exists — And Where It Falls Short</h3><p>Before building anything, I spent time seriously evaluating the best existing options. Two stood out.</p><h3><a href="https://reduxkotlin.org/">ReduxKotlin</a></h3><p><a href="https://reduxkotlin.org/">ReduxKotlin</a> is a faithful, well-maintained Kotlin port of JavaScript Redux. It has the same API — store, reducer, getState, dispatch — which makes it instantly familiar if you&#39;ve ever worked with JS Redux. It supports middleware, which is genuinely great.</p><p>But the moment you need async work, you hit the wall. To do anything asynchronous, you need a middleware that lets you dispatch <em>functions</em> instead of actions. A thunk looks like this:</p><pre>store.dispatch { dispatch, getState -&gt;<br>    val result = repository.loadItems()<br>    dispatch(CartAction.CartLoaded(result))<br>}</pre><p>This works, but it has real costs. You’re dispatching a lambda — an opaque, untestable value — rather than a typed, inspectable action. There is no compile-time constraint on what the thunk is allowed to dispatch back. A CartThunk can accidentally dispatch a DeliveryAction and the compiler says nothing. Asserting in tests what a thunk <em>did</em> requires either mocking the store or capturing dispatched calls in a wrapper. There is no built-in effect system, no lens-based reducer composition, and no pullback mechanism. Combining reducers follows the JS Redux model of combineReducers — a flat, manual slice declaration with no optics.</p><h3><a href="https://github.com/toggl/komposable-architecture">Komposable Architecture</a> by Toggl</h3><p><a href="https://github.com/toggl/komposable-architecture">Komposable Architecture</a> is the most direct <a href="https://github.com/pointfreeco/swift-composable-architecture">TCA</a> port for Android I found — Toggl built it explicitly as a Kotlin adaptation of Point-Free’s work, and it shows. Reducers are pure functions, effects are typed values that emit actions via Flow, and state composition is supported through a pullback mechanism.</p><p>But look at what that pullback actually requires:</p><p>PullbackReducer(<br> innerReducer = cartReducer,<br> mapToLocalState = { globalState -&gt; globalState.cart },<br> mapToLocalAction = { globalAction -&gt; globalAction as? CartAction },<br> mapToGlobalState = { globalState, localState -&gt; globalState.copy(cart = localState) },<br> mapToGlobalAction = { localAction -&gt; CheckoutAction.Cart(localAction) },<br>)</p><p>Four mapping functions per feature. For a checkout screen with three sub-features — cart, delivery, place order — that is twelve mapping lambdas declared before you’ve written a single line of business logic. For a screen with five sub-features, it’s twenty.</p><p>There is also no traditional middleware — cross-cutting concerns like logging are handled through higher-order reducers, which means wrapping reducers inside other reducers. Navigation support is described in the <a href="https://github.com/toggl/komposable-architecture">Komposable Architecture</a> README as an <em>“early exploration”</em> of how the architecture could work with Navigation 3. The testing API requires a testReduce callback lambda rather than a chainable assertion DSL. These are not signs of a poorly-made library — <a href="https://github.com/toggl/komposable-architecture">Komposable Architecture</a> is well-engineered and the closest thing to <a href="https://github.com/pointfreeco/swift-composable-architecture">TCA</a> on Android that existed — but the ergonomic friction accumulates meaningfully at production scale.</p><h3>Introducing <a href="https://github.com/atwa/komposed">Komposed</a></h3><p><a href="https://github.com/atwa/komposed">Komposed</a> is a lightweight Kotlin library for predictable, testable, composable state management on Android. It adapts the fundamental building blocks of <a href="https://github.com/pointfreeco/swift-composable-architecture">TCA</a> — reducers, typed effects, lenses, and middleware — to idiomatic Kotlin and Jetpack Compose.</p><p>The guiding principle was simple: every architectural layer should have exactly one job, and doing that job should require the minimum possible code.</p><h3>Architecture at a Glance</h3><blockquote><em>The diagram below shows how a single dispatched action travels through the entire pipeline — from the UI, through middleware, into the reducer, and back out through effects and subscriptions.</em></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DRBz4Ox4a8Gieb2hgmHYiA.jpeg" /></figure><h3>The Architecture: One Job Per Layer</h3><h3>Reducer — State Management, Nothing Else</h3><p>A Reducer in <a href="https://github.com/atwa/komposed">Komposed</a> is a pure function. It receives the current state and an action, and it returns a ReduceType — either a new state, a new state plus an effect to launch, or just an effect with no state change.</p><pre>val cartReducer = reducer&lt;CartState, CartAction&gt; { state, action -&gt;<br>    when (action) {<br>        CartAction.LoadCart -&gt;<br>            state.copy(isLoading = true).withEffect { CartEffect.Load }</pre><pre>        is CartAction.CartLoaded -&gt;<br>            state.copy(items = action.items, isLoading = false).reduce()</pre><pre>        is CartAction.CartFailed -&gt;<br>            state.copy(isLoading = false, error = action.message).reduce()<br>    }<br>}</pre><p>No I/O. No coroutines. No injected dependencies. No knowledge of where data comes from. The reducer’s entire job is computing the next state — and expressing intent to do async work as a typed value, not as a lambda.</p><p>This is the key structural choice that separates <a href="https://github.com/atwa/komposed">Komposed</a> from thunk-based approaches. Effects are values you can inspect, assert, and route — not opaque functions you have to mock around.</p><h3>EffectHandler — Side Effects, Nothing Else</h3><p>An EffectHandler performs the async work the reducer described. It receives an effect, does its work, and dispatches zero, one, or many actions back into the store. It never touches state directly.</p><pre>class CartEffectHandlerImpl @Inject constructor(<br>    private val repository: CartRepository,<br>) : EffectHandler&lt;CartEffect, CartAction&gt; {</pre><pre>    override suspend fun handle(<br>        effect: CartEffect,<br>        dispatch: suspend (suspend () -&gt; CartAction) -&gt; Unit,<br>    ) {<br>        when (effect) {<br>            CartEffect.Load -&gt; dispatch {<br>                repository.getItems().fold(<br>                    onSuccess = { CartAction.CartLoaded(it) },<br>                    onFailure = { CartAction.CartFailed(it.message ?: &quot;Unknown error&quot;) },<br>                )<br>            }<br>        }<br>    }<br>}</pre><p>The dispatch { } lambda runs on Dispatchers.IO, and the resulting action is automatically posted back to the main thread by the store. The type parameter A is enforced at compile time — a CartEffectHandler cannot accidentally dispatch a DeliveryAction. This is a guarantee thunks simply cannot provide.</p><h3>Store — Orchestration, Nothing Else</h3><p>The store routes every dispatched action through the middleware chain, invokes the matching reducer, updates state, and launches any emitted effects on the IO dispatcher. Client code passes a plain viewModelScope — no dispatcher wrangling, no thread pinning.</p><pre>val store = createStore(<br>    initialValue = CheckoutState(),<br>    scope        = viewModelScope,<br>    middlewares  = listOf(loggingMiddleware(), navigationMiddleware(navigator)),<br>    reducers = reducers {<br>        cartReducer.scoped(CheckoutState.cartLens)<br>        deliveryReducer.scoped(CheckoutState.deliveryLens)<br>        placeOrderReducer.scoped(CheckoutState.placeOrderLens)<br>    },<br>    effectHandlers = effectHandlers {<br>        cartEffectHandler.register()<br>        deliveryEffectHandler.register()<br>        placeOrderEffectHandler.register()<br>    },<br>    subscriptions = subscriptions {<br>        subscription(<br>            selector = { it.deliveryState.selectedAddress?.deliveryFee ?: 0.0 },<br>            action   = { BillAction.DeliveryFeeUpdated(it) },<br>        )<br>    },<br>)</pre><h3>Middleware — Cross-Cutting Concerns, Nothing Else</h3><p>Middleware intercepts every dispatched action before it reaches a reducer. Logging, analytics, A/B flags, navigation — none of it belongs in business logic, and none of it needs to.</p><pre>fun &lt;S&gt; loggingMiddleware() = createMiddleware&lt;S&gt; { _, action, next -&gt;<br>    Log.d(&quot;Komposed&quot;, &quot;→ ${action::class.simpleName}&quot;)<br>    next(action)<br>}</pre><p>The built-in navigationMiddleware intercepts NavigationEffect — a sealed marker the reducer emits just like any other effect — and executes it against a Navigator. The NavController never appears in a ViewModel or reducer. This is how navigation is correctly a side effect of state transitions, not a direct call.</p><p>This is one of the sharpest practical differences from <a href="https://github.com/toggl/komposable-architecture">Komposable Architecture</a>: <a href="https://github.com/atwa/komposed">Komposed</a> has first-class middleware, so you never need to wrap reducers inside other reducers to add cross-cutting behaviour.</p><h3>Composability: Solving Real Production Complexity</h3><p>This is where the architecture earns its name.</p><p>Real production screens are not simple. A checkout screen might combine cart state, delivery address selection, billing summary, and order placement — four distinct domains, each with its own async operations, each potentially reacting to changes in the others. The conventional approach ends up as one enormous ViewModel, with one enormous state class, and one enormous when-block that knows far too much about everything.</p><p><a href="https://github.com/atwa/komposed">Komposed</a> addresses this with lens-based state composition. A Lens&lt;GLOBAL, LOCAL&gt; is a getter/setter pair, declared once as a companion:</p><pre>data class CheckoutState(<br>    val cart:       CartState       = CartState(),<br>    val delivery:   DeliveryState   = DeliveryState(),<br>    val placeOrder: PlaceOrderState = PlaceOrderState(),<br>) {<br>    companion object {<br>        val cartLens       = lens(CheckoutState::cart)       { copy(cart = it) }<br>        val deliveryLens   = lens(CheckoutState::delivery)   { copy(delivery = it) }<br>        val placeOrderLens = lens(CheckoutState::placeOrder) { copy(placeOrder = it) }<br>    }<br>}</pre><p>Pulling a local reducer up to global state is then one line:</p><pre>cartReducer.scoped(CheckoutState.cartLens)</pre><p>Each sub-feature lives in its own Gradle module. DeliveryReducer has zero knowledge of CartState. The checkout screen is their <em>composition</em>, not their owner. Adding a fourth feature — say, a promo code module — is three lines in the store registration. Nothing else changes.</p><p>Compare this to <a href="https://github.com/toggl/komposable-architecture">Komposable Architecture</a>’s four-mapping-function pullback, or to <a href="https://reduxkotlin.org/">ReduxKotlin</a>’s combineReducers, which works but offers no optics abstraction — every new slice is a new manual mapping.</p><h3>Subscriptions: Reactive Cross-Domain Coordination</h3><p>Composable features raise an interesting problem at production scale: how does one feature react to state changes in another, without importing it?</p><p>Consider a checkout screen. The bill summary needs to reflect the delivery fee — which lives in DeliveryModule. But BillModule is a standalone Gradle module with no dependency on DeliveryModule. Adding an import would collapse the boundary the entire architecture is designed to protect.</p><p><a href="https://github.com/atwa/komposed">Komposed</a> solves this with subscriptions: a lightweight mechanism that watches a derived value of the global state and automatically dispatches an action whenever that value changes. The wiring lives at the composition boundary — the ViewModel — where both modules are visible. Neither module needs to know about the other.</p><pre>val store = createStore(<br>    ...<br>    subscriptions = subscriptions {<br>        subscription(<br>            selector = { it.deliveryState.selectedAddress?.deliveryFee ?: 0.0 },<br>            action   = { BillAction.DeliveryFeeUpdated(it) },<br>        )<br>    },<br>)</pre><p>BillModule only needs one new action and one reducer case:</p><pre>data class DeliveryFeeUpdated(val fee: Double) : BillAction</pre><pre>is BillAction.DeliveryFeeUpdated -&gt; state.copy(deliveryFees = action.fee).reduce()</pre><p>Subscriptions fire after every state update. If selector(prevState) == selector(newState) nothing is dispatched — there is no loop risk, because DeliveryFeeUpdated only mutates billState.deliveryFees, not the delivery address the selector watches. The dispatched action re-enters the full middleware chain, so it is logged, analytics-tracked, and fully observable.</p><p>A note on when to use subscriptions. Subscriptions solve the specific problem of values that need to cross a module boundary — where neither module can import the other. Values derived entirely within one module’s own state don’t need them. BillState owns orderTotal, serviceFees, and deliveryFees, so its grand total is simply a derived property:</p><pre>data class BillState(<br>    val serviceFees: Double = 0.0,<br>    val orderTotal:  Double = 0.0,<br>    val deliveryFees: Double = 0.0,<br>    val isLoading:   Boolean = false,<br>) {<br>    val grandTotal: Double get() = orderTotal + serviceFees + deliveryFees<br>}</pre><p>No action, no subscription, no extra dispatch. The module computes what it already knows; the subscription carries only what it cannot see.</p><p>The cross-domain wire-up is fully testable without any mocks or event buses:</p><pre>@Test<br>fun `selecting a delivery address pushes its fee into BillState via subscription`() = runTest {<br>    val store = buildStore(this)<br>    store.dispatch(DeliveryAction.FetchDeliveryAddresses)<br>    advanceUntilIdle()<br>    store.dispatch(DeliveryAction.OnDeliveryAddressSelected(1L))<br>    assert(store.state.value.billState.deliveryFees == 10.0)<br>    assert(store.state.value.billState.grandTotal == 10.0)<br>}</pre><p>One declaration at the composition boundary. Both modules stay clean.</p><h3>Unidirectional Data Flow: Predictable by Construction</h3><p>Every state change in <a href="https://github.com/atwa/komposed">Komposed</a> follows one path:</p><pre>Action → Middleware → Reducer → State + Effect → EffectHandler → Action → …</pre><p>There is no way to mutate state from a coroutine, a callback, or a side channel. State is always a deterministic function of the actions that preceded it. This means any bug can be reproduced by replaying the action sequence, and any behaviour can be understood by reading a pure function — the reducer — with no hidden inputs.</p><p>It also means the UDF contract is impossible to accidentally violate. The framework enforces it at the type level.</p><h3>Testability: Assert What Your App Actually Does</h3><p>This is where I wanted <a href="https://github.com/atwa/komposed">Komposed</a> to shine most.</p><h3>Reducer Tests — No Coroutines, No Mocks</h3><pre>@Test<br>fun `LoadCart sets isLoading and emits Load effect`() {<br>    cartReducer.given(CartState(), CartAction.LoadCart)<br>        .assertState(CartState(isLoading = true))<br>        .assertEffect&lt;CartEffect.Load&gt;()<br>}</pre><pre>@Test<br>fun `CartFailed stores the error message`() {<br>    cartReducer<br>        .given(CartState(isLoading = true), CartAction.CartFailed(&quot;Timeout&quot;))<br>        .assertState(CartState(isLoading = false, error = &quot;Timeout&quot;))<br>        .assertNoEffect()<br>}</pre><p>Pure functions need no coroutines, no TestScope, no fakes. The test reads exactly like a specification.</p><h3>Effect Handler Tests — Dispatched Actions as a List</h3><p>The komposed-testing module provides a handle(effect) extension that collects every dispatched action and returns them as List&lt;A&gt;:</p><pre>@Test<br>fun `Load dispatches CartLoaded on success`() = runTest {<br>    val result = handlerWith(successRepo).handle(CartEffect.Load)<br>    assert(result.single() == CartAction.CartLoaded(items))<br>}</pre><pre>@Test<br>fun `Load dispatches CartFailed with message on failure`() = runTest {<br>    val result = handlerWith(failureRepo).handle(CartEffect.Load)<br>    assert(result.single() == CartAction.CartFailed(&quot;Network error&quot;))<br>}</pre><p>No capture variables. No lambdas passed in. No mock dispatch function to wire up. The API surface is deliberately minimal.</p><h3>Integration Tests — Assert the Full Action Sequence</h3><p>TestStore records every dispatched action in order — including actions produced by effect handlers — so you can assert not just final state but the exact flow your app took to get there:</p><pre>@Test<br>fun `LoadCart effect round-trip updates state`() = runTest {<br>    val store = buildStore(this)<br>    store.dispatch(CartAction.LoadCart)<br>    advanceUntilIdle()<br>    store.assertState(CheckoutState(cart = CartState(items = listOf(testItem))))<br>    store.assertActionsDispatched(CartAction.LoadCart, CartAction.CartLoaded(testItem))<br>}</pre><h3>Navigation Tests — Effects, Not Mocks</h3><p>Navigation in <a href="https://github.com/atwa/komposed">Komposed</a> is a typed effect. That means it’s assertable the same way any other effect is:</p><pre>@Test<br>fun `OrderPlaced navigates to OrderDetails with the correct ID`() {<br>    placeOrderReducer<br>        .given(PlaceOrderState(), PlaceOrderAction.OrderPlaced(orderId = &quot;ORD-99&quot;))<br>        .assertNavigationEffect { nav -&gt;<br>            assert(nav.navigations.last() == OrderDetailsRoute(orderId = &quot;ORD-99&quot;))<br>        }<br>}</pre><p>TestNavigator records every navigate(), navigateUp(), and popBackStack() call. No Robolectric. No instrumented test. No mock NavController.</p><h3>Side-by-Side Comparison</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8z3D3DjMKAiHkyVwlmfLCQ.png" /></figure><p><a href="https://reduxkotlin.org/">ReduxKotlin</a> is a solid Redux port, but the thunk middleware loses type safety at exactly the boundary where it matters most — the async/dispatch boundary. <a href="https://github.com/toggl/komposable-architecture">Komposable Architecture</a> is the closest prior work to what I set out to build, and it deserves recognition for that. But four mapping functions per pullback and no middleware mean that the ergonomic cost grows with every domain you add to a screen.</p><h3>A Library for the Team That Wants to Ship</h3><p>My iOS friend eventually built his Android project. He used <a href="https://github.com/atwa/komposed">Komposed</a>. His feedback after a few weeks was the same as mine:</p><blockquote>“It just gets out of the way.”</blockquote><p>You define your state, write a pure reducer, implement an effect handler, and wire them together in a store. The framework handles threading, effect routing, action type-safety, and testing infrastructure. You handle your app.</p><p>The architecture is explicitly inspired by <a href="https://github.com/pointfreeco/swift-composable-architecture">TCA</a> — the same ideas of pure reducers, typed effects, composable lenses, and first-class testability that iOS engineers have come to rely on. <a href="https://github.com/atwa/komposed">Komposed</a> is the answer to the question my friend asked that Tuesday evening.</p><h3>Get Started</h3><pre>implementation(&quot;io.github.atwa:komposed:1.1.0&quot;)<br>testImplementation(&quot;io.github.atwa:komposed-testing:1.1.0&quot;)</pre><p>Source, documentation, and the full sample checkout app: https://github.com/Atwa/Komposed</p><p><em>Inspired by </em><a href="https://github.com/pointfreeco/swift-composable-architecture"><em>The Composable Architecture</em></a><em> by Point-Free.</em></p><p>Tags: Android · Kotlin · Architecture · JetpackCompose · StateManagement · TCA · UDF · MVI</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c924610d9aa7" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>