<?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 Glafira Privalova on Medium]]></title>
        <description><![CDATA[Stories by Glafira Privalova on Medium]]></description>
        <link>https://medium.com/@glaphi?source=rss-61903eebf9d1------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*j_cvd8zAyFHGtV5k.jpg</url>
            <title>Stories by Glafira Privalova on Medium</title>
            <link>https://medium.com/@glaphi?source=rss-61903eebf9d1------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 03 Dec 2026 12:53:48 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@glaphi/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[TCA Performance Best Practices: Avoid Capturing Whole @ObservableState in Effects]]></title>
            <link>https://medium.com/@glaphi/tca-performance-best-practices-avoid-capturing-whole-observablestate-in-effects-25804c021c69?source=rss-61903eebf9d1------2</link>
            <guid isPermaLink="false">https://medium.com/p/25804c021c69</guid>
            <category><![CDATA[cats]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[swiftui]]></category>
            <category><![CDATA[xcode]]></category>
            <category><![CDATA[debugging]]></category>
            <dc:creator><![CDATA[Glafira Privalova]]></dc:creator>
            <pubDate>Fri, 01 Aug 2025 12:51:35 GMT</pubDate>
            <atom:updated>2025-08-01T12:51:35.771Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*spzcZcu-Fh57aaPLsF9N5A.png" /></figure><h3>Short @ObservableState recap</h3><p>Since TCA 1.7, a reducer’s state can be annotated with @ObservableState.</p><p>Behind the scenes the macro:</p><ul><li>inserts a hidden <strong>reference-type registrar</strong> that tracks every read/write</li><li>injects a unique identifier so SwiftUI can diff changes</li><li>expects <strong>all</strong> reads and writes to come from the <strong>main actor</strong></li></ul><p>That last bullet is critical: if you touch the registrar off the main actor you will first see runtime warnings and, in nastier cases, memory-corruption crashes. The Swift forums still remind us that “publishing changes from background threads is not allowed” when working with observation-based models .</p><h3>Why the temptation is dangerous</h3><p>A common pattern when converting older TCA features is to grab the whole state in a capture list and use it later inside an Effect.run:</p><pre>return .run { [state] send in               // ❌ problematic<br>  await send(.delegate(state.information))<br>}</pre><p>On the surface this feels harmless: the state is a value struct, after all. But two subtle facts combine into trouble.</p><p>Reference semantics are hidden inside the struct: the copy still carries the registrar object, so any read or write hits shared reference data.<br>Effect.run starts off the main actor: unless you mark the closure @MainActor, the body begins on the cooperative thread-pool, and hops only <em>after</em> the first await, and may never hop back if there’s no suspension point.</p><p>Consequences you can observe in apps:</p><ul><li><strong>Perceptible warnings `</strong>state was accessed but is not being tracked` spam in Xcode’s console (sadly, there are false positive warning as well)</li><li><strong>Crashes: </strong>touching the registrar off-actor can dereference already-deallocated memory (<strong>EXC_BAD_ACCESS)</strong></li><li><strong>Out-of-order UI: </strong>mixed main and background mutations confuse SwiftUI diffing, leading to stale rows or flickering animations</li></ul><h3>Safer, more performant patterns</h3><p>Extract only what you need on the main actor</p><pre>// Extract only what you need on the main actor<br><br>let information = state.information<br><br>return .run { send in<br>  await send(.delegate(information))  // safe registrar-free value<br>}<br><br>// If you need many fields, make sendable data transfer objects (DTO)<br><br>struct Information{<br>  let id: String<br>  let name: String<br>  let isPremium: Bool<br>}<br><br>....<br><br>let information = Information(id: state.id, name: state.name, isPremium: state.isPremium)<br><br>return .run { send in<br>   send(.delegate(information))  // safe registrar-free value<br>}</pre><p>When you must call other async api inside your effect you can isolate it to @MainActor. That way the entire closure runs on the main actor, and you still get TCA’s effect lifecycle such as cancellation and scoping.</p><p>If, after refactoring, all you do in the asynchronous run is send one action, you can replace it with a direct send.</p><pre>// you would be able to replace<br>return .run { @MainActor send in<br>  send(.someAction)<br>}<br><br>// with a direct send<br>return .send(.someAction)</pre><h3>Why This Works</h3><p>Actor-hopping rules. Async closures without actor isolation start on a background executor. By reading registrar-bearing state <em>before</em> that boundary, you honor the main-actor contract.</p><p>Created registrar-free value types are Sendable. Only simple Swift types cross concurrency domains so there are no warnings, no crashes.</p><p>Lean, predictable store. Fewer off-thread writes means fewer reducer runs, simpler diffing, and faster UI updates.</p><h3>Refactoring Checklist</h3><p><strong>Search</strong> your codebase for unsafe patterns like:</p><pre>Effect.run { [state] in ... }<br>Effect.run { [... = state] in ... }<br>Task { [state] in ... }</pre><p>The simplest way to locate problematic patterns is to use <strong>regular expression</strong> search in Xcode.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*2HTP6uolV4MmCKfyuM-x5g.png" /><figcaption><strong>regular expression search in Xcode</strong></figcaption></figure><p>Just enable “Regular Expression” option in the search panel (⌘⇧F), and paste in a regex like this:</p><pre>state\](?:\s|\n)*send(?:\s|\n)*in</pre><p>This expression matches cases where state is captured and later passed into a send call, potentially off the main actor.</p><p>Then make it safer and cleaner:</p><ul><li>Replace each capture with <strong>explicit value extraction on the main actor</strong>. If multiple fields are needed, snapshot them into a sendable DTO</li><li>Audit @MainActor .run closures and try swapping trivial ones to simple <strong>.send</strong> for safety</li><li><strong>Test under Thread Sanitizer </strong>that warnings and crashes disappeared</li><li>Use <strong>Instruments</strong> and slow animations to verify that UI updates are smoother</li><li><strong>Use TCA.printChanges()</strong> to better understand reducer behaviour and avoid unnecessary updates</li></ul><h3>Conclusion</h3><p>@ObservableState brings powerful, dynamic UI binding to TCA, but it also embeds a hidden registrar that <em>must</em> stay on the main actor. That means <strong>every touch matters</strong>, especially when crossing concurrency boundaries. Capturing your entire state into an <em>asynchronous</em> background effect can violate this contract, leading to warnings, crashes, and UI instability.</p><p>Always pause before capturing the whole state. Instead, be mindful of actor hopping: capture only what you need and isolate state access to the main actor. These steps eliminate threading warnings, prevent crashes, and keep your UI fast.</p><p>Don’t assume behaviour since Swift and TCA are constantly evolving. Keeping your code lean now is a valuable investment that prepares your codebase for <a href="https://www.pointfree.co/blog/posts/180-perception-2-0-an-updated-back-port-of-swift-s-observation-framework">Perception 2.0</a>’s richer macros, async observations, and deeper Swift Concurrency integrations.</p><p>Happy coding! 🚀</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=25804c021c69" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[TCA Performance Best Practices: Return Effects Directly]]></title>
            <link>https://medium.com/@glaphi/tca-performance-best-practices-return-effects-directly-4c73de02e01b?source=rss-61903eebf9d1------2</link>
            <guid isPermaLink="false">https://medium.com/p/4c73de02e01b</guid>
            <category><![CDATA[performance]]></category>
            <category><![CDATA[composable-architecture]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[tips]]></category>
            <category><![CDATA[best-practices]]></category>
            <dc:creator><![CDATA[Glafira Privalova]]></dc:creator>
            <pubDate>Wed, 11 Jun 2025 09:56:43 GMT</pubDate>
            <atom:updated>2025-06-11T09:56:43.319Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*spzcZcu-Fh57aaPLsF9N5A.png" /></figure><p><strong>The Composable Architecture (TCA)</strong> is powerful, but subtle differences in how you handle effects can have surprising consequences. In this article, we’ll explore why returning effects directly, rather than chaining extra .send actions, leads to better performance, more flexible code, and cleaner tests.</p><h3>Short TCA recap</h3><p>TCA applies a unidirectional data flow similar to Redux:</p><pre>state → view → action → reducer → (new) state</pre><p><strong>Store </strong>is the single source of truth: it holds the state tree, routes actions to the reducer, runs effects the reducer returns, and publishes updated state to the UI.</p><p><strong>Reducer </strong>is a pure function that receives the current state and an action, synchronously produces the next state, and may return an Effect describing side work.</p><p><strong>Effect </strong>is a unit of asynchronous work (<em>network requests, timers, async streams, etc</em>), as it completes or emits values, it can dispatch new actions back to the store.</p><p>Essential effect helpers:</p><ul><li>.send(action): emit exactly one action, that completes synchronously after enqueuing the action</li><li>.run { send in … }: run asynchronous code over time, sending zero or more actions<em> (supersedes formerly soft deprecated .task and .fireAndForget)</em></li><li>.concatenate<strong> </strong>and<strong> </strong>.merge: combine multiple effects and start them in series or in parallel respectively</li></ul><p><strong>State</strong> remains the single source of truth, <strong>actions</strong> are the <em>only</em> way it changes, and <strong>effects</strong> bridge the synchronous reducer with the asynchronous world. Understanding how these pieces fit together is key to writing efficient, predictable and performant code in TCA.</p><h3>The tempting pattern</h3><p>When coordinating asynchronous work in TCA, you might be tempted to dispatch each step as its own action. Reducer body might look something like this:</p><pre>// Chaining .send actions: no blocking, seems to work<br>.concatenate {<br>  .send(firstAction)<br>  .send(secondAction) // enqueues and completes immediately<br>  .send(thirdAction)<br>}</pre><p>Because each .send(..) dispatches its action into the store, enqueues its action and completes instantly, the chain never waits for the reducer work those actions trigger, so later steps fire anyway. That can hide race conditions and it comes with hidden costs.</p><h3>Three costs of over-sending</h3><p>From <a href="https://pointfreeco.github.io/swift-composable-architecture/main/documentation/composablearchitecture/performance/#High-frequency-actions">TCA Performance Guide → High‑frequency actions</a>:</p><blockquote><em>Sending actions comes with a cost. You should aim to only send “</em><strong><em>significant</em></strong><em>” actions into the system.</em></blockquote><p>Sending an action is not a cheap method call — each action travels through the entire feature tree. Each layer gets a chance to intercept the action, run its reducer logic, render views, and start more effects.</p><p>Main drawbacks:</p><ul><li><strong>Extra store work:</strong> every helper action ripples through all features, triggering extra reducer runs and view updates. On complex screens this can noticeably slow things down.</li><li><strong>Rigid ordering:</strong> helper action fired with .send always runs after the current reducer case, any store mutations performed by the original action would happen first. You lose flexibility.</li><li><strong>Complex tests: </strong>TestStore scripts need to expect and handle each send(..) with a corresponding receive(..), assert on interim state, and then continue. Tests become verbose and harder to read, hiding the real flow.</li></ul><p>The guide’s recommendation is clear: <strong>only send “significant” actions, </strong>those that map directly to a user intent or deliver data back from an effect. All other logic belongs in helper methods that return effects.</p><h3>Return an effect instead of another action</h3><p>Move shared or long‑running logic into a helper that returns an Effect instead of another action.</p><pre>.concatenate {<br>  .send(firstAction)<br>  secondActionEffect(&amp;state) // constructed Effect<br>  .send(thirdAction)<br>}<br><br>...<br><br>func secondActionEffect(_ state: inout State) -&gt; Effect&lt;Action&gt; {<br>  // mutate state, build and return effect...<br>}</pre><p>All work happens inside one action eliminating internal .send overhead. You gain full control over ordering of mutations and actions, and keep tests simple. The chain of concatenated execution is now correctly <strong>blocked </strong>until the return Effect work is fully finished.</p><h3>So what if the effect never ends?</h3><p>What would happen if secondActionEffect() was awaiting for an asyncSequence?</p><pre>func secondActionEffect(_ state: inout State) -&gt; Effect&lt;Action&gt; {<br>  // potential state mutations<br>  .run { send in<br>    for await update in try await api.updatesStream() {<br>      await send(.streamResponse(update))<br>    }<br>  }<br>}</pre><p>Because the stream stays alive, a .concatenate after it will wait for that effect to end (e.g. sequence onTermination) before continuing to any concatenated calls. That might be expected behaviour or it might block later work. If you need both serial and long-running work, refactor as shown below.</p><h3>Refactoring a concatenate chain</h3><p>When you find a .concatenate with a lot of .send actions, use this checklist<strong>:</strong></p><ol><li>Extract long-running or reusable work:<strong> </strong>move it into helper functions that return an Effect, helperMethod() -&gt; Effect&lt;Action&gt;</li><li>Keep short truly serial effects together: leave only quick, strictly ordered steps inside a single.concatenate</li><li>Launch helpers and the serial chain independently: wrap both the extracted helpers and the .concatenate block in the .merge so they fire immediately and independently</li></ol><pre>// BEFORE<br><br>.concatenate {<br>  .send(firstAction)    // serial step 1 (quick)<br>  .send(secondAction)   // serial step 2 (long-running)<br>  .send(thirdAction)    // serial step 3 (quick)<br>}<br><br>// AFTER<br>.merge(<br>  .concatenate {<br>    firstActionEffect(&amp;state)   // step 1: quick Effect<br>    .send(thirdAction)          // step 3: must remain an action (e.g. delegate)<br>  },<br>  secondActionEffect()          // step 2: heavy, long-running Effect, now parallel<br>)</pre><h3>Conclusion</h3><p>Next time you’re tempted to insert multiple .send calls just to coordinate logic, pause and ask:</p><blockquote>“Does this really deserve its own action?”</blockquote><ul><li>if <strong>no</strong>: return an effect directly from a helper method</li><li>merge helpers that can run in parallel</li><li>concatenate only what must remain strictly ordered</li></ul><p>You’ll enjoy a faster store, more flexible sequences, and tests that read like a clear story rather than a debugging script.</p><p>Happy coding! 🚀</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4c73de02e01b" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>