{"@attributes":{"version":"2.0"},"channel":{"title":"ionostafi.com","link":"https:\/\/ionostafi.com","description":"About software development","generator":"Zola","language":"en","lastBuildDate":"Wed, 03 Jun 2026 00:00:00 +0000","item":[{"title":"SwiftUI Concurrency Pattern: Bind Async Tasks to View State","pubDate":"Wed, 03 Jun 2026 00:00:00 +0000","author":"Ion Ostafi","link":"https:\/\/ionostafi.com\/blog\/swiftui-concurrency-task-view-lifecycle\/","guid":"https:\/\/ionostafi.com\/blog\/swiftui-concurrency-task-view-lifecycle\/","description":"<p>Starting async work in SwiftUI looks easy. But very quickly, lifecycle problems appear.<\/p>\n<p>If the user leaves the screen, what should happen to the task?\nIf they tap the same button twice, should the previous work be canceled?\nWhere should cancellation logic live?<\/p>\n<p>I wanted a plain solution: clear lifecycle behavior, small code, and no custom abstraction.<\/p>\n<h2 id=\"the-problem\">The problem<\/h2>\n<p>There are a few common ways to start async work in SwiftUI. They all work, but each one has a cost.<\/p>\n<h3 id=\"1-start-from-a-synchronous-viewmodel-function-create-a-task-inside\">1) Start from a synchronous ViewModel function, create a <code>Task<\/code> inside<\/h3>\n<p>This is the most common pattern:<\/p>\n<pre data-lang=\"swift\" class=\"language-swift z-code\"><code class=\"language-swift\" data-lang=\"swift\"><span class=\"z-source z-swift\"><span class=\"z-meta z-function-declaration z-swift\"><span class=\"z-storage z-type z-function z-swift\">func<\/span> <span class=\"z-entity z-type z-function z-swift\">runAction<\/span><span class=\"z-meta z-parameter-clause z-swift\"><span class=\"z-punctuation z-definition z-function-arguments z-begin z-swift\">(<\/span><span class=\"z-punctuation z-definition z-function-arguments z-end z-swift\">)<\/span><\/span> <span class=\"z-punctuation z-definition z-code-block z-begin z-swift\">{<\/span>\n<\/span><\/span><span class=\"z-source z-swift\"><span class=\"z-meta z-function-declaration z-swift\">    Task {\n<\/span><\/span><span class=\"z-source z-swift\"><span class=\"z-meta z-function-declaration z-swift\">        await action()\n<\/span><\/span><span class=\"z-source z-swift\"><span class=\"z-meta z-function-declaration z-swift\">    <span class=\"z-punctuation z-definition z-code-block z-end z-swift\">}<\/span><\/span>\n<\/span><span class=\"z-source z-swift\">}\n<\/span><\/code><\/pre>\n<p>It solves the fact that a <code>Button<\/code> action is sync, but now lifecycle becomes the ViewModel\u2019s responsibility:<\/p>\n<ul>\n<li>keep a reference to the newly created <code>Task<\/code><\/li>\n<li>cancel it at the right time<\/li>\n<li>avoid duplicated in-flight work<\/li>\n<\/ul>\n<p>So cancellation and view lifecycle details leak into the ViewModel.<\/p>\n<h3 id=\"2-create-task-in-the-view-itself\">2) Create <code>Task<\/code> in the view itself<\/h3>\n<p>You can also do:<\/p>\n<pre data-lang=\"swift\" class=\"language-swift z-code\"><code class=\"language-swift\" data-lang=\"swift\"><span class=\"z-source z-swift\">Button(<span class=\"z-meta z-literal z-string z-swift\"><span class=\"z-string z-quoted z-double z-swift\">&quot;<\/span><span class=\"z-string z-quoted z-double z-swift\">R<\/span><span class=\"z-string z-quoted z-double z-swift\">u<\/span><span class=\"z-string z-quoted z-double z-swift\">n<\/span><span class=\"z-string z-quoted z-double z-swift\"> <\/span><span class=\"z-string z-quoted z-double z-swift\">a<\/span><span class=\"z-string z-quoted z-double z-swift\">c<\/span><span class=\"z-string z-quoted z-double z-swift\">t<\/span><span class=\"z-string z-quoted z-double z-swift\">i<\/span><span class=\"z-string z-quoted z-double z-swift\">o<\/span><span class=\"z-string z-quoted z-double z-swift\">n<\/span><span class=\"z-string z-quoted z-double z-swift\">&quot;<\/span><\/span>) {\n<\/span><span class=\"z-source z-swift\">    Task {\n<\/span><span class=\"z-source z-swift\">        await viewModel<span class=\"z-keyword z-operator z-custom z-postfix z-unary z-swift\">.<\/span>runAction()\n<\/span><span class=\"z-source z-swift\">    }\n<\/span><span class=\"z-source z-swift\">}\n<\/span><\/code><\/pre>\n<p>But this brings back the same lifecycle problem. You still need to decide when and where to cancel.<\/p>\n<h2 id=\"swift-by-sundell-s-asyncbutton\">Swift by Sundell\u2019s AsyncButton<\/h2>\n<p>Swift by Sundell <a href=\"https:\/\/www.swiftbysundell.com\/articles\/building-an-async-swiftui-button\/\">explained this problem well<\/a> with an <code>AsyncButton<\/code> abstraction.<\/p>\n<p>The main benefit is clear: async behavior is wrapped in a reusable API, and cancellation is hidden from call sites.<\/p>\n<p>Still, the core mechanism depends on manual cancel. It is cleaner, but still manual.<\/p>\n<h2 id=\"a-plain-state-driven-solution-with-task-id\">A plain state-driven solution with <code>.task(id:)<\/code><\/h2>\n<p>My preferred base solution is simple: make state transitions explicit, then bind side effects with <code>.task(id:)<\/code>.<\/p>\n<p>ViewModel state:<\/p>\n<pre data-lang=\"swift\" class=\"language-swift z-code\"><code class=\"language-swift\" data-lang=\"swift\"><span class=\"z-source z-swift\"><span class=\"z-storage z-modifier z-attribute z-swift\"><span class=\"z-punctuation z-definition z-attribute z-swift\">@<\/span>Published<\/span> <span class=\"z-storage z-type z-swift\">var<\/span> operationState: OperationState <span class=\"z-keyword z-operator z-assignment z-swift\">=<\/span> <span class=\"z-keyword z-operator z-custom z-prefix z-unary z-swift\">.<\/span>idle\n<\/span><\/code><\/pre>\n<p>Trigger from UI (important part):<\/p>\n<pre data-lang=\"swift\" class=\"language-swift z-code\"><code class=\"language-swift\" data-lang=\"swift\"><span class=\"z-source z-swift\">Button(<span class=\"z-meta z-literal z-string z-swift\"><span class=\"z-string z-quoted z-double z-swift\">&quot;<\/span><span class=\"z-string z-quoted z-double z-swift\">R<\/span><span class=\"z-string z-quoted z-double z-swift\">u<\/span><span class=\"z-string z-quoted z-double z-swift\">n<\/span><span class=\"z-string z-quoted z-double z-swift\"> <\/span><span class=\"z-string z-quoted z-double z-swift\">a<\/span><span class=\"z-string z-quoted z-double z-swift\">c<\/span><span class=\"z-string z-quoted z-double z-swift\">t<\/span><span class=\"z-string z-quoted z-double z-swift\">i<\/span><span class=\"z-string z-quoted z-double z-swift\">o<\/span><span class=\"z-string z-quoted z-double z-swift\">n<\/span><span class=\"z-string z-quoted z-double z-swift\">&quot;<\/span><\/span>) {\n<\/span><span class=\"z-source z-swift\">    <span class=\"z-comment z-line z-double-slash z-swift\"><span class=\"z-punctuation z-definition z-comment z-line z-double-slash z-swift\">\/\/<\/span> Because state is Hashable, we can ignore guarding against multiple taps here. The task will only run once per state change.<\/span>\n<\/span><span class=\"z-source z-swift\">    viewModel<span class=\"z-keyword z-operator z-custom z-postfix z-unary z-swift\">.<\/span>operationState <span class=\"z-keyword z-operator z-assignment z-swift\">=<\/span> <span class=\"z-keyword z-operator z-custom z-prefix z-unary z-swift\">.<\/span>running\n<\/span><span class=\"z-source z-swift\">}\n<\/span><\/code><\/pre>\n<aside class=\"alert\"><p>There is a small mindset shift here:<\/p>\n<p>A) Have an async function, call it, manage its lifecycle manually.<\/p>\n<p>B) Have a state, update the state, react to the state to start work, then update the state again when work finishes.<\/p>\n<p>In this article, we use option B.<\/p>\n<\/aside>\n<p>View:<\/p>\n<pre data-lang=\"swift\" class=\"language-swift z-code\"><code class=\"language-swift\" data-lang=\"swift\"><span class=\"z-source z-swift\"><span class=\"z-comment z-line z-double-slash z-swift\"><span class=\"z-punctuation z-definition z-comment z-line z-double-slash z-swift\">\/\/<\/span> task(id:) makes sure the closure is called only when state changes<\/span>\n<\/span><span class=\"z-source z-swift\"><span class=\"z-keyword z-operator z-custom z-postfix z-unary z-swift\">.<\/span>task(id: viewModel<span class=\"z-keyword z-operator z-custom z-postfix z-unary z-swift\">.<\/span>operationState) {\n<\/span><span class=\"z-source z-swift\">    <span class=\"z-keyword z-control z-if z-swift\">if<\/span> viewModel<span class=\"z-keyword z-operator z-custom z-postfix z-unary z-swift\">.<\/span>operationState <span class=\"z-keyword z-operator z-comparative z-swift\">==<\/span> <span class=\"z-keyword z-operator z-custom z-prefix z-unary z-swift\">.<\/span>running {\n<\/span><span class=\"z-source z-swift\">        await viewModel<span class=\"z-keyword z-operator z-custom z-postfix z-unary z-swift\">.<\/span>runAction()\n<\/span><span class=\"z-source z-swift\">        viewModel<span class=\"z-keyword z-operator z-custom z-postfix z-unary z-swift\">.<\/span>operationState <span class=\"z-keyword z-operator z-assignment z-swift\">=<\/span> <span class=\"z-keyword z-operator z-custom z-prefix z-unary z-swift\">.<\/span>idle\n<\/span><span class=\"z-source z-swift\">    }\n<\/span><span class=\"z-source z-swift\">}\n<\/span><\/code><\/pre>\n<p>Why this works:<\/p>\n<ul>\n<li>the task is attached to the view lifecycle<\/li>\n<li>when the view disappears, SwiftUI cancels the task automatically<\/li>\n<li>state drives effects, so intent is explicit (<code>.idle -&gt; .running -&gt; .idle<\/code>)<\/li>\n<li>no need to keep a <code>Task<\/code> handle in the ViewModel for this flow<\/li>\n<\/ul>\n<p>This keeps the ViewModel focused on state and business logic, while SwiftUI owns the task lifecycle.<\/p>\n<h2 id=\"loading-indicator-only-if-work-takes-long\">Loading indicator only if work takes long<\/h2>\n<p>Another important point from the AsyncButton discussion is UX:\noften we want a loading indicator only if the operation is not very fast.<\/p>\n<p>A nice way to do it is to combine state-driven rendering with delayed animation, without using <code>sleep<\/code> APIs:<\/p>\n<pre data-lang=\"swift\" class=\"language-swift z-code\"><code class=\"language-swift\" data-lang=\"swift\"><span class=\"z-source z-swift\"><span class=\"z-keyword z-other z-access-level-modifier z-swift\">private<\/span> <span class=\"z-storage z-type z-swift\">var<\/span> isPerformingTask: <span class=\"z-support z-type z-swift\">Bool<\/span> {\n<\/span><span class=\"z-source z-swift\">    viewModel<span class=\"z-keyword z-operator z-custom z-postfix z-unary z-swift\">.<\/span>operationState <span class=\"z-keyword z-operator z-comparative z-swift\">==<\/span> <span class=\"z-keyword z-operator z-custom z-prefix z-unary z-swift\">.<\/span>running\n<\/span><span class=\"z-source z-swift\">}\n<\/span><span class=\"z-source z-swift\">\n<\/span><span class=\"z-source z-swift\"><span class=\"z-keyword z-other z-access-level-modifier z-swift\">private<\/span> <span class=\"z-storage z-type z-swift\">var<\/span> actionRow: some View {\n<\/span><span class=\"z-source z-swift\">    HStack {\n<\/span><span class=\"z-source z-swift\">        Button(<span class=\"z-meta z-literal z-string z-swift\"><span class=\"z-string z-quoted z-double z-swift\">&quot;<\/span><span class=\"z-string z-quoted z-double z-swift\">R<\/span><span class=\"z-string z-quoted z-double z-swift\">u<\/span><span class=\"z-string z-quoted z-double z-swift\">n<\/span><span class=\"z-string z-quoted z-double z-swift\"> <\/span><span class=\"z-string z-quoted z-double z-swift\">a<\/span><span class=\"z-string z-quoted z-double z-swift\">c<\/span><span class=\"z-string z-quoted z-double z-swift\">t<\/span><span class=\"z-string z-quoted z-double z-swift\">i<\/span><span class=\"z-string z-quoted z-double z-swift\">o<\/span><span class=\"z-string z-quoted z-double z-swift\">n<\/span><span class=\"z-string z-quoted z-double z-swift\">&quot;<\/span><\/span>) {\n<\/span><span class=\"z-source z-swift\">            viewModel<span class=\"z-keyword z-operator z-custom z-postfix z-unary z-swift\">.<\/span>operationState <span class=\"z-keyword z-operator z-assignment z-swift\">=<\/span> <span class=\"z-keyword z-operator z-custom z-prefix z-unary z-swift\">.<\/span>running\n<\/span><span class=\"z-source z-swift\">        }\n<\/span><span class=\"z-source z-swift\">        <span class=\"z-keyword z-operator z-custom z-prefix z-unary z-swift\">.<\/span>task(id: viewModel<span class=\"z-keyword z-operator z-custom z-postfix z-unary z-swift\">.<\/span>operationState) {\n<\/span><span class=\"z-source z-swift\">            <span class=\"z-keyword z-control z-if z-swift\">if<\/span> viewModel<span class=\"z-keyword z-operator z-custom z-postfix z-unary z-swift\">.<\/span>operationState <span class=\"z-keyword z-operator z-comparative z-swift\">==<\/span> <span class=\"z-keyword z-operator z-custom z-prefix z-unary z-swift\">.<\/span>running {\n<\/span><span class=\"z-source z-swift\">                await viewModel<span class=\"z-keyword z-operator z-custom z-postfix z-unary z-swift\">.<\/span>runAction()\n<\/span><span class=\"z-source z-swift\">                viewModel<span class=\"z-keyword z-operator z-custom z-postfix z-unary z-swift\">.<\/span>operationState <span class=\"z-keyword z-operator z-assignment z-swift\">=<\/span> <span class=\"z-keyword z-operator z-custom z-prefix z-unary z-swift\">.<\/span>idle\n<\/span><span class=\"z-source z-swift\">            }\n<\/span><span class=\"z-source z-swift\">        }\n<\/span><span class=\"z-source z-swift\">\n<\/span><span class=\"z-source z-swift\">        <span class=\"z-keyword z-control z-if z-swift\">if<\/span> isPerformingTask {\n<\/span><span class=\"z-source z-swift\">            ProgressView()\n<\/span><span class=\"z-source z-swift\">                <span class=\"z-keyword z-operator z-custom z-prefix z-unary z-swift\">.<\/span>progressViewStyle(<span class=\"z-keyword z-operator z-custom z-prefix z-unary z-swift\">.<\/span>circular)\n<\/span><span class=\"z-source z-swift\">                <span class=\"z-keyword z-operator z-custom z-prefix z-unary z-swift\">.<\/span>transition(<span class=\"z-keyword z-operator z-custom z-prefix z-unary z-swift\">.<\/span>opacity)\n<\/span><span class=\"z-source z-swift\">        }\n<\/span><span class=\"z-source z-swift\">    }\n<\/span><span class=\"z-source z-swift\">    <span class=\"z-keyword z-operator z-custom z-prefix z-unary z-swift\">.<\/span>animation(<span class=\"z-keyword z-operator z-custom z-prefix z-unary z-swift\">.<\/span>linear<span class=\"z-keyword z-operator z-custom z-postfix z-unary z-swift\">.<\/span>delay(<span class=\"z-constant z-numeric z-integer z-decimal z-swift\">0<\/span><span class=\"z-keyword z-operator z-custom z-postfix z-unary z-swift\">.<\/span><span class=\"z-constant z-numeric z-integer z-decimal z-swift\">15<\/span>), value: isPerformingTask)\n<\/span><span class=\"z-source z-swift\">}\n<\/span><\/code><\/pre>\n<p>That <code>delay(0.15)<\/code> helps a lot:<\/p>\n<ul>\n<li>quick operations finish before the spinner appears<\/li>\n<li>longer than 0.15 seconds operations still show progress feedback<\/li>\n<li>no artificial delay in business logic<\/li>\n<li>no <code>Task.sleep<\/code> coordination code<\/li>\n<\/ul>\n<p>Simple, explicit, and easy to reason about.<\/p>\n<h2 id=\"final-note\">Final note<\/h2>\n<p>This is a plain solution, not a framework.<\/p>\n<p>If needed, you can hide it later behind custom API (<code>AsyncButton<\/code>, view modifier, custom control). But starting with plain state + <code>.task(id:)<\/code> keeps behavior obvious and lifecycle-safe from day one.<\/p>\n"},{"title":"Swift enum and modular design","pubDate":"Tue, 11 Nov 2025 00:00:00 +0000","author":"Ion Ostafi","link":"https:\/\/ionostafi.com\/blog\/swift-mod-enum\/","guid":"https:\/\/ionostafi.com\/blog\/swift-mod-enum\/","description":"<p>I\u2019ve been thinking about Swift enums lately, especially how we use them in modular architectures. They\u2019re fantastic until they\u2019re not - and that transition happens quietly.<\/p>\n<pre data-lang=\"swift\" class=\"language-swift z-code\"><code class=\"language-swift\" data-lang=\"swift\"><span class=\"z-source z-swift\"><span class=\"z-storage z-type z-swift\">enum<\/span> ErrorReason {\n<\/span><span class=\"z-source z-swift\">    <span class=\"z-keyword z-control z-switch z-swift\">case<\/span> timeout\n<\/span><span class=\"z-source z-swift\">    <span class=\"z-keyword z-control z-switch z-swift\">case<\/span> invalidResponse\n<\/span><span class=\"z-source z-swift\">    <span class=\"z-keyword z-control z-switch z-swift\">case<\/span> serverError(<span class=\"z-support z-type z-swift\">Int<\/span>)\n<\/span><span class=\"z-source z-swift\">}\n<\/span><\/code><\/pre>\n<p>This looks innocent enough. Every Swift developer has written something similar. The problem emerges when this enum lives in a shared module and suddenly three different modules need to extend it with their own error cases.<\/p>\n<p>Here\u2019s an alternative approach I\u2019ve been experimenting with:<\/p>\n<pre data-lang=\"swift\" class=\"language-swift z-code\"><code class=\"language-swift\" data-lang=\"swift\"><span class=\"z-source z-swift\"><span class=\"z-comment z-line z-double-slash z-swift\"><span class=\"z-punctuation z-definition z-comment z-line z-double-slash z-swift\">\/\/<\/span> Module: Core<\/span>\n<\/span><span class=\"z-source z-swift\"><span class=\"z-storage z-type z-swift\">struct<\/span> ErrorReason {\n<\/span><span class=\"z-source z-swift\">    <span class=\"z-keyword z-other z-access-level-modifier z-swift\">public<\/span> <span class=\"z-storage z-type z-swift\">let<\/span> value: <span class=\"z-support z-type z-swift\">String<\/span>\n<\/span><span class=\"z-source z-swift\">\n<\/span><span class=\"z-source z-swift\">    <span class=\"z-keyword z-other z-access-level-modifier z-swift\">public<\/span> <span class=\"z-keyword z-other z-declaration-modifier z-swift\">static<\/span> <span class=\"z-storage z-type z-swift\">var<\/span> unknown <span class=\"z-keyword z-operator z-assignment z-swift\">=<\/span> <span class=\"z-keyword z-other z-statement z-swift\">Self<\/span>(<span class=\"z-meta z-literal z-string z-swift\"><span class=\"z-string z-quoted z-double z-swift\">&quot;<\/span><span class=\"z-string z-quoted z-double z-swift\">u<\/span><span class=\"z-string z-quoted z-double z-swift\">n<\/span><span class=\"z-string z-quoted z-double z-swift\">k<\/span><span class=\"z-string z-quoted z-double z-swift\">n<\/span><span class=\"z-string z-quoted z-double z-swift\">o<\/span><span class=\"z-string z-quoted z-double z-swift\">w<\/span><span class=\"z-string z-quoted z-double z-swift\">n<\/span><span class=\"z-string z-quoted z-double z-swift\">&quot;<\/span><\/span>)\n<\/span><span class=\"z-source z-swift\">}\n<\/span><span class=\"z-source z-swift\">\n<\/span><span class=\"z-source z-swift\"><span class=\"z-comment z-line z-double-slash z-swift\"><span class=\"z-punctuation z-definition z-comment z-line z-double-slash z-swift\">\/\/<\/span> Other modules can define their own error reasons<\/span>\n<\/span><span class=\"z-source z-swift\"><span class=\"z-comment z-line z-double-slash z-swift\"><span class=\"z-punctuation z-definition z-comment z-line z-double-slash z-swift\">\/\/<\/span> Module: Subscription<\/span>\n<\/span><span class=\"z-source z-swift\"><span class=\"z-keyword z-other z-access-level-modifier z-swift\">internal<\/span> <span class=\"z-storage z-type z-swift\">extension<\/span> ErrorReason {\n<\/span><span class=\"z-source z-swift\">    <span class=\"z-keyword z-other z-declaration-modifier z-swift\">static<\/span> <span class=\"z-storage z-type z-swift\">var<\/span> storeKitFailure <span class=\"z-keyword z-operator z-assignment z-swift\">=<\/span> <span class=\"z-keyword z-other z-statement z-swift\">Self<\/span>(<span class=\"z-meta z-literal z-string z-swift\"><span class=\"z-string z-quoted z-double z-swift\">&quot;<\/span><span class=\"z-string z-quoted z-double z-swift\">s<\/span><span class=\"z-string z-quoted z-double z-swift\">t<\/span><span class=\"z-string z-quoted z-double z-swift\">o<\/span><span class=\"z-string z-quoted z-double z-swift\">r<\/span><span class=\"z-string z-quoted z-double z-swift\">e<\/span><span class=\"z-string z-quoted z-double z-swift\">K<\/span><span class=\"z-string z-quoted z-double z-swift\">i<\/span><span class=\"z-string z-quoted z-double z-swift\">t<\/span><span class=\"z-string z-quoted z-double z-swift\">F<\/span><span class=\"z-string z-quoted z-double z-swift\">a<\/span><span class=\"z-string z-quoted z-double z-swift\">i<\/span><span class=\"z-string z-quoted z-double z-swift\">l<\/span><span class=\"z-string z-quoted z-double z-swift\">u<\/span><span class=\"z-string z-quoted z-double z-swift\">r<\/span><span class=\"z-string z-quoted z-double z-swift\">e<\/span><span class=\"z-string z-quoted z-double z-swift\">&quot;<\/span><\/span>)\n<\/span><span class=\"z-source z-swift\">}\n<\/span><span class=\"z-source z-swift\">\n<\/span><span class=\"z-source z-swift\"><span class=\"z-comment z-line z-double-slash z-swift\"><span class=\"z-punctuation z-definition z-comment z-line z-double-slash z-swift\">\/\/<\/span> Module: Account<\/span>\n<\/span><span class=\"z-source z-swift\"><span class=\"z-keyword z-other z-access-level-modifier z-swift\">internal<\/span> <span class=\"z-storage z-type z-swift\">extension<\/span> ErrorReason {\n<\/span><span class=\"z-source z-swift\">    <span class=\"z-keyword z-other z-declaration-modifier z-swift\">static<\/span> <span class=\"z-storage z-type z-swift\">var<\/span> invalidAccount <span class=\"z-keyword z-operator z-assignment z-swift\">=<\/span> <span class=\"z-keyword z-other z-statement z-swift\">Self<\/span>(<span class=\"z-meta z-literal z-string z-swift\"><span class=\"z-string z-quoted z-double z-swift\">&quot;<\/span><span class=\"z-string z-quoted z-double z-swift\">i<\/span><span class=\"z-string z-quoted z-double z-swift\">n<\/span><span class=\"z-string z-quoted z-double z-swift\">v<\/span><span class=\"z-string z-quoted z-double z-swift\">a<\/span><span class=\"z-string z-quoted z-double z-swift\">l<\/span><span class=\"z-string z-quoted z-double z-swift\">i<\/span><span class=\"z-string z-quoted z-double z-swift\">d<\/span><span class=\"z-string z-quoted z-double z-swift\">A<\/span><span class=\"z-string z-quoted z-double z-swift\">c<\/span><span class=\"z-string z-quoted z-double z-swift\">c<\/span><span class=\"z-string z-quoted z-double z-swift\">o<\/span><span class=\"z-string z-quoted z-double z-swift\">u<\/span><span class=\"z-string z-quoted z-double z-swift\">n<\/span><span class=\"z-string z-quoted z-double z-swift\">t<\/span><span class=\"z-string z-quoted z-double z-swift\">&quot;<\/span><\/span>)\n<\/span><span class=\"z-source z-swift\">}\n<\/span><\/code><\/pre>\n<p>It\u2019s more verbose, but each module can define its own error types without touching shared code. The tradeoff is losing some of Swift\u2019s pattern matching elegance while gaining modularity and extensibility.<\/p>\n<p>This lets each module contribute types or cases without central coordination. I\u2019ve noticed this same pattern in the Swift StoreKit API, where <code>paymentMode<\/code> is a struct with static instances rather than an enum.<\/p>\n<p>I\u2019m not suggesting abandoning enums entirely. They\u2019re perfect for truly closed sets - compass directions, HTTP methods, parsing states. The key is recognizing when a set <em>feels<\/em> closed but might actually need to be open.<\/p>\n<p>The question arises - why not use the Error protocol, or create a protocol and extend it in each module? The challenge there is losing the shared type that groups all error reasons together. Using a struct with static instances maintains a common type while allowing extensions.<\/p>\n<p>This example is part of a larger attempt at having a common error handling strategy across modules while preserving modularity:<\/p>\n<pre data-lang=\"swift\" class=\"language-swift z-code\"><code class=\"language-swift\" data-lang=\"swift\"><span class=\"z-source z-swift\"><span class=\"z-keyword z-other z-access-level-modifier z-swift\">public<\/span> <span class=\"z-storage z-type z-swift\">struct<\/span> ApplicationError: Error, Equatable {\n<\/span><span class=\"z-source z-swift\">    <span class=\"z-comment z-line z-double-slash z-swift\"><span class=\"z-punctuation z-definition z-comment z-line z-double-slash z-swift\">\/\/<\/span> Open structure instead of enum<\/span>\n<\/span><span class=\"z-source z-swift\">    <span class=\"z-keyword z-other z-access-level-modifier z-swift\">public<\/span> <span class=\"z-storage z-type z-swift\">let<\/span> recoveryHint: ApplicationErrorRecoveryHint\n<\/span><span class=\"z-source z-swift\">    <span class=\"z-comment z-line z-double-slash z-swift\"><span class=\"z-punctuation z-definition z-comment z-line z-double-slash z-swift\">\/\/<\/span> Open structure instead of enum<\/span>\n<\/span><span class=\"z-source z-swift\">    <span class=\"z-keyword z-other z-access-level-modifier z-swift\">public<\/span> <span class=\"z-storage z-type z-swift\">let<\/span> reason: ApplicationErrorReason\n<\/span><span class=\"z-source z-swift\">    <span class=\"z-keyword z-other z-access-level-modifier z-swift\">public<\/span> <span class=\"z-storage z-type z-swift\">let<\/span> message: <span class=\"z-support z-type z-swift\">String<\/span>\n<\/span><span class=\"z-source z-swift\">    <span class=\"z-comment z-line z-double-slash z-swift\"><span class=\"z-punctuation z-definition z-comment z-line z-double-slash z-swift\">\/\/<\/span> Open structure instead of enum<\/span>\n<\/span><span class=\"z-source z-swift\">    <span class=\"z-keyword z-other z-access-level-modifier z-swift\">public<\/span> <span class=\"z-storage z-type z-swift\">let<\/span> origin: ApplicationErrorOrigin\n<\/span><span class=\"z-source z-swift\">    <span class=\"z-keyword z-other z-access-level-modifier z-swift\">public<\/span> <span class=\"z-storage z-type z-swift\">let<\/span> code: <span class=\"z-support z-type z-swift\">Int<\/span>\n<\/span><span class=\"z-source z-swift\">    <span class=\"z-keyword z-other z-access-level-modifier z-swift\">public<\/span> <span class=\"z-storage z-type z-swift\">let<\/span> file: <span class=\"z-support z-type z-swift\">String<\/span>\n<\/span><span class=\"z-source z-swift\">    <span class=\"z-keyword z-other z-access-level-modifier z-swift\">public<\/span> <span class=\"z-storage z-type z-swift\">let<\/span> line: <span class=\"z-support z-type z-swift\">UInt<\/span>\n<\/span><span class=\"z-source z-swift\">}\n<\/span><\/code><\/pre>\n<p>The entire application uses <code>ApplicationError<\/code> across all modules, but each module can define its own reasons, recovery hints, and origins without touching shared code. Cross-cutting concerns are defined in the core module, while feature modules extend them as needed.<\/p>\n<p>This approach trades compile-time exhaustiveness for runtime flexibility. In modular systems, that might be the right tradeoff.<\/p>\n"},{"title":"TVGrid: The 3-Day Bet That Fixed a Frozen Xbox Home Screen","pubDate":"Thu, 25 Sep 2025 00:00:00 +0000","author":"Ion Ostafi","link":"https:\/\/ionostafi.com\/crunchyroll\/custom-grid-js\/","guid":"https:\/\/ionostafi.com\/crunchyroll\/custom-grid-js\/","description":"<blockquote>\n<p>Short version: A persistent half\u2011second feeling freeze on an Xbox streaming app vanished after replacing a stack of generic layout\/navigation helpers with ~3 focused days of bespoke geometry + focus modeling. This is the story, the decision framework, and the transferable lessons.<\/p>\n<\/blockquote>\n<h2 id=\"problem-context\">Problem Context<\/h2>\n<p>In 2018\u20132019 I was one of four engineers building the VRV streaming app for Xbox One using React + TypeScript. It had to feel native to a game console: instant directional focus jumps, graceful motion, no dropped frames, no waiting. One afternoon a pattern emerged\u2014we would navigate back to Home and for a beat the interface just froze. Not a crash. A brief stall long enough to break immersion and remind you there was a browser under the hood. On a large screen, that hitch is trust erosion.<\/p>\n<p>Content growth caused it. Marketing kept adding rails (rows). Design wanted sticky headers and asymmetric groupings. The more eclectic the layout became, the more the generic layout + navigation helpers buckled. Libraries gave us abstractions; the Xbox controller demanded guarantees. I let the problem idle in the background\u2014sketching rectangles, rehearsing focus paths mentally\u2014until the model felt inevitable. Then I cleared three days and built what became \u201cTVGrid\u201d.<\/p>\n<p><img src=\"https:\/\/ionostafi.com\/crunchyroll\/custom-grid-js\/Demo.gif\" alt=\"TVGrid demo \u2013 smooth controller focus transitions without freezes\" title=\"TVGrid navigation demo\" \/><\/p>\n<h2 id=\"the-moment-of-decision\">The Moment of Decision<\/h2>\n<p>The choice was not \u201cbuild a grid\u201d versus \u201cuse one\u201d. It was: continue patching around opaque behavior, or own the mental model governing focus, scroll, and anchoring. The existing approach fought us\u2014layout reflows, unpredictable fallback focus, hidden performance costs. A lean in\u2011house layer could instead: precompute space, move only transforms, and never guess.<\/p>\n<h2 id=\"a-three-day-sprint\">A Three-Day Sprint<\/h2>\n<p>Day 1: carve the world into deterministic rectangles on paper; translate them into a data structure the runtime can trust.<\/p>\n<p>Day 2: wire controller intent (up, down, left, right) directly to geometry instead of DOM heuristics.<\/p>\n<p>Day 3: sand edges\u2014off\u2011screen items fade in; headers feel fixed without hacks; guardrails for edge cases.<\/p>\n<p>After that it looked like it had \u201calways been there\u201d.<\/p>\n<p>From the product perspective we hadn\u2019t added a feature; we had removed a sensation: waiting.<\/p>\n<h2 id=\"what-actually-changed\">What Actually Changed<\/h2>\n<p>Here\u2019s where the story shifts: Instead of relying on the browser\u2019s layout engine to figure out where things should go, the grid took charge. Every cell, every header, every element was given an exact set of coordinates\u2014absolute positions, mapped out ahead of time like seats in a theater. When you pressed a button, the grid didn\u2019t ask the browser to shuffle things around; it simply animated the movement, sliding the whole view smoothly to reveal the next set of content.<\/p>\n<p>Scrolling wasn\u2019t a negotiation with the DOM\u2014it was a choreography. The grid used animation to move the visible window, making transitions feel intentional and fluid. The result was a UI that felt alive and responsive, not just technically correct but emotionally satisfying. The magic wasn\u2019t in the code\u2014it was in the feeling that every movement was exactly where it belonged, every time.<\/p>\n<h2 id=\"decision-framework-build-vs-buy\">Decision Framework (Build vs Buy)<\/h2>\n<p>Build a bespoke layer when:<\/p>\n<ul>\n<li>Latency is user\u2011visible and tied to abstraction overhead you cannot easily profile or trim.<\/li>\n<li>You need guarantees (deterministic focus paths) rather than heuristics.<\/li>\n<li>The conceptual surface of a custom solution is genuinely smaller than the workaround surface area.<\/li>\n<li>You can articulate the entire mental model on a whiteboard in &lt; 10 minutes.<\/li>\n<\/ul>\n<p>Do not build when:<\/p>\n<ul>\n<li>Requirements are still volatile and exploration speed matters more than determinism.<\/li>\n<li>Commodity solutions already meet 90% of user experience targets.<\/li>\n<li>Your team lacks a maintainer willing to own the core primitive.<\/li>\n<\/ul>\n<h2 id=\"what-success-looked-like\">What Success Looked Like<\/h2>\n<ul>\n<li>Perceived freeze removed (qualitative measurement\u2014no instrumentation snapshot retained).<\/li>\n<li>Controller navigation felt \u201cinevitable\u201d: no accidental diagonal drift, no mis\u2011focus recovery flicker.<\/li>\n<li>Designers stopped flagging \u201cheader jitter\u201d in reviews.<\/li>\n<li>Another engineer shipped a minor enhancement post\u2011handoff without consulting me.<\/li>\n<\/ul>\n<h2 id=\"when-not-to-rebuild\">When Not To Rebuild<\/h2>\n<p>Don\u2019t chase novelty. If the freeze had been solvable by instrumentation + tuning existing libraries, that was cheaper. The inflection point was when mental simulation of a simpler model was clearer than explaining another workaround PR.<\/p>\n<h2 id=\"lessons-learned\">Lessons Learned<\/h2>\n<ol>\n<li>Small, purpose\u2011built layers unlock performance and clarity when generic abstractions hide the levers you actually need.<\/li>\n<li>Precomputation trades minor upfront work for durable runtime calm.<\/li>\n<li>\u201cFeel\u201d bugs benefit from narrative rehearsal before code\u2014walk the user path mentally until a simpler invariant emerges.<\/li>\n<li>Maintenance risk shrinks when the code embodies one named idea with crisp boundaries.<\/li>\n<li>Success metrics can be qualitative if they map to human perception (responsiveness) and are paired with a clear regression story.<\/li>\n<\/ol>\n<p>TVGrid served thousands of cells without drama. It never became a sprawling framework; it stayed a sharp tool. After I moved on, another engineer extended it with minimal ceremony\u2014that counted as validation.<\/p>\n<h2 id=\"aftermath-reflection\">Aftermath &amp; Reflection<\/h2>\n<p>The product was eventually sunset (as many are). The grid never shipped as open source; it didn\u2019t need to. Its value was local: restoring responsiveness, reinforcing a culture of owning interaction primitives, and proving that \u201cwe can build this\u201d can be the safest, fastest path.<\/p>\n<p>If you\u2019ve got a UI freeze that keeps returning like a creak in a house, tell yourself the story of how it should work\u2014end to end\u2014without naming libraries. If that story is short and stable, you may already have the spec for the lean piece of software that will fix it.<\/p>\n<h2 id=\"key-takeaways\">Key Takeaways<\/h2>\n<ul>\n<li>Eliminating a tiny pause can lift perceived quality more than adding a new carousel.<\/li>\n<li>Sometimes \u201ccustom build\u201d means fewer moving parts, not more.<\/li>\n<li>Clear mental models make future iteration cheaper.<\/li>\n<\/ul>\n<h2 id=\"closing-thought\">Closing Thought<\/h2>\n<p>Great platform experiences are often defined not by adding one more animation, but by removing the invisible tax of hesitation. TVGrid was the removal of hesitation.<\/p>\n<!-- No implementation code retained: this retelling is intentionally narrative for mixed technical \/ non\u2011technical audiences. -->\n"},{"title":"Swift event bus","pubDate":"Wed, 13 Aug 2025 00:00:00 +0000","author":"Ion Ostafi","link":"https:\/\/ionostafi.com\/blog\/swift-event-bus-design\/","guid":"https:\/\/ionostafi.com\/blog\/swift-event-bus-design\/","description":"<p>While working on the M25 app, I realized I needed a more structured approach to event handling. This post outlines the design of a simple event bus implementation in Swift. It improves on the initial design <a href=\"https:\/\/ionostafi.com\/blog\/ios-event-driven-architecture\/#simple-event-bus-design-using-swift-and-combine\">here<\/a>.<\/p>\n<h2 id=\"a-naive-event-bus-built-on-combine\">A naive event bus built on Combine<\/h2>\n<p>Before the details, here\u2019s how it\u2019s used.\nThis is a naive event bus: intentionally minimal, clear, and best suited for prototypes or small modules; you can harden it later with policies, filtering, and scheduling.<\/p>\n<pre data-lang=\"swift\" class=\"language-swift z-code\"><code class=\"language-swift\" data-lang=\"swift\"><span class=\"z-source z-swift\"><span class=\"z-comment z-line z-double-slash z-swift\"><span class=\"z-punctuation z-definition z-comment z-line z-double-slash z-swift\">\/\/<\/span> Define the event with a payload<\/span>\n<\/span><span class=\"z-source z-swift\"><span class=\"z-storage z-type z-swift\">class<\/span> SongsShuffled: EventBase<span class=\"z-keyword z-operator z-comparative z-swift\">&lt;<\/span>ShuffledPlaylist<span class=\"z-keyword z-operator z-comparative z-swift\">&gt;<\/span> { }\n<\/span><span class=\"z-source z-swift\">\n<\/span><span class=\"z-source z-swift\"><span class=\"z-comment z-line z-double-slash z-swift\"><span class=\"z-punctuation z-definition z-comment z-line z-double-slash z-swift\">\/\/<\/span> Send a SongsShuffled event with a ShuffledPlaylist payload over the bus<\/span>\n<\/span><span class=\"z-source z-swift\">eventBus<span class=\"z-keyword z-operator z-custom z-postfix z-unary z-swift\">.<\/span>send(DomainEvent<span class=\"z-keyword z-operator z-custom z-postfix z-unary z-swift\">.<\/span>SongsShuffled(ShuffledPlaylist<span class=\"z-keyword z-operator z-custom z-postfix z-unary z-swift\">.<\/span>sample()))\n<\/span><span class=\"z-source z-swift\">\n<\/span><span class=\"z-source z-swift\"><span class=\"z-comment z-line z-double-slash z-swift\"><span class=\"z-punctuation z-definition z-comment z-line z-double-slash z-swift\">\/\/<\/span> Listen to event and assign to a @Published<\/span>\n<\/span><span class=\"z-source z-swift\">eventBus<span class=\"z-keyword z-operator z-custom z-postfix z-unary z-swift\">.<\/span>receive(DomainEvent<span class=\"z-keyword z-operator z-custom z-postfix z-unary z-swift\">.<\/span>SongsShuffled<span class=\"z-keyword z-operator z-custom z-postfix z-unary z-swift\">.<\/span><span class=\"z-keyword z-other z-statement z-swift\">self<\/span>)\n<\/span><span class=\"z-source z-swift\">    <span class=\"z-keyword z-operator z-custom z-prefix z-unary z-swift\">.<\/span>map(\\<span class=\"z-keyword z-operator z-custom z-postfix z-unary z-swift\">.<\/span>payload<span class=\"z-keyword z-operator z-custom z-postfix z-unary z-swift\">.<\/span>songs)\n<\/span><span class=\"z-source z-swift\">    <span class=\"z-keyword z-operator z-custom z-prefix z-unary z-swift\">.<\/span>receive(on: DispatchQueue<span class=\"z-keyword z-operator z-custom z-postfix z-unary z-swift\">.<\/span>main)\n<\/span><span class=\"z-source z-swift\">    <span class=\"z-keyword z-operator z-custom z-prefix z-unary z-swift\">.<\/span>assign(to: <span class=\"z-keyword z-operator z-bitwise z-swift\">&amp;<\/span>$shuffledSongs)\n<\/span><\/code><\/pre>\n<h2 id=\"naive-implementation\">Naive implementation<\/h2>\n<p>The minimal code required for the naive bus to work.<\/p>\n<pre data-lang=\"swift\" class=\"language-swift z-code\"><code class=\"language-swift\" data-lang=\"swift\"><span class=\"z-source z-swift\"><span class=\"z-keyword z-other z-access-level-modifier z-swift\">public<\/span> <span class=\"z-storage z-type z-swift\">protocol<\/span> EventProtocol: CustomStringConvertible {\n<\/span><span class=\"z-source z-swift\">    associatedtype Payload\n<\/span><span class=\"z-source z-swift\">\n<\/span><span class=\"z-source z-swift\">    <span class=\"z-storage z-type z-swift\">var<\/span> generationDate: Date { <span class=\"z-keyword z-other z-swift\">get<\/span> }\n<\/span><span class=\"z-source z-swift\">    <span class=\"z-storage z-type z-swift\">var<\/span> id: UUID { <span class=\"z-keyword z-other z-swift\">get<\/span> }\n<\/span><span class=\"z-source z-swift\">    <span class=\"z-storage z-type z-swift\">var<\/span> name: <span class=\"z-support z-type z-swift\">String<\/span> { <span class=\"z-keyword z-other z-swift\">get<\/span> }\n<\/span><span class=\"z-source z-swift\">    <span class=\"z-storage z-type z-swift\">var<\/span> source: <span class=\"z-support z-type z-swift\">String<\/span> { <span class=\"z-keyword z-other z-swift\">get<\/span> }\n<\/span><span class=\"z-source z-swift\">    <span class=\"z-storage z-type z-swift\">var<\/span> payload: Payload { <span class=\"z-keyword z-other z-swift\">get<\/span> }\n<\/span><span class=\"z-source z-swift\">}\n<\/span><span class=\"z-source z-swift\">\n<\/span><span class=\"z-source z-swift\"><span class=\"z-keyword z-other z-access-level-modifier z-swift\">open<\/span> <span class=\"z-storage z-type z-swift\">class<\/span> EventBase<span class=\"z-keyword z-operator z-comparative z-swift\">&lt;<\/span>Payload<span class=\"z-keyword z-operator z-comparative z-swift\">&gt;<\/span>: EventProtocol {\n<\/span><span class=\"z-source z-swift\">    <span class=\"z-keyword z-other z-access-level-modifier z-swift\">public<\/span> <span class=\"z-storage z-type z-swift\">let<\/span> generationDate: Date <span class=\"z-keyword z-operator z-assignment z-swift\">=<\/span> <span class=\"z-keyword z-operator z-custom z-prefix z-unary z-swift\">.<\/span>now\n<\/span><span class=\"z-source z-swift\">    <span class=\"z-keyword z-other z-access-level-modifier z-swift\">public<\/span> <span class=\"z-storage z-type z-swift\">let<\/span> id: UUID <span class=\"z-keyword z-operator z-assignment z-swift\">=<\/span> <span class=\"z-keyword z-operator z-custom z-prefix z-unary z-swift\">.<\/span><span class=\"z-keyword z-declaration z-swift\">init<\/span>()\n<\/span><span class=\"z-source z-swift\">    <span class=\"z-keyword z-other z-access-level-modifier z-swift\">public<\/span> <span class=\"z-storage z-type z-swift\">let<\/span> name: <span class=\"z-support z-type z-swift\">String<\/span>\n<\/span><span class=\"z-source z-swift\">    <span class=\"z-keyword z-other z-access-level-modifier z-swift\">public<\/span> <span class=\"z-storage z-type z-swift\">let<\/span> source: <span class=\"z-support z-type z-swift\">String<\/span>\n<\/span><span class=\"z-source z-swift\">    <span class=\"z-keyword z-other z-access-level-modifier z-swift\">public<\/span> <span class=\"z-storage z-type z-swift\">let<\/span> payload: Payload\n<\/span><span class=\"z-source z-swift\">\n<\/span><span class=\"z-source z-swift\">    <span class=\"z-keyword z-other z-access-level-modifier z-swift\">public<\/span> <span class=\"z-keyword z-declaration z-swift\">init<\/span>(_ payload: Payload, _ source: <span class=\"z-support z-type z-swift\">String<\/span> <span class=\"z-keyword z-operator z-assignment z-swift\">=<\/span> #file) {\n<\/span><span class=\"z-source z-swift\">        <span class=\"z-keyword z-other z-statement z-swift\">self<\/span><span class=\"z-keyword z-operator z-custom z-postfix z-unary z-swift\">.<\/span>source <span class=\"z-keyword z-operator z-assignment z-swift\">=<\/span> URL(string: source)?<span class=\"z-keyword z-operator z-custom z-postfix z-unary z-swift\">.<\/span>lastPathComponent ?? source\n<\/span><span class=\"z-source z-swift\">        <span class=\"z-keyword z-other z-statement z-swift\">self<\/span><span class=\"z-keyword z-operator z-custom z-postfix z-unary z-swift\">.<\/span>payload <span class=\"z-keyword z-operator z-assignment z-swift\">=<\/span> payload\n<\/span><span class=\"z-source z-swift\">        <span class=\"z-keyword z-other z-statement z-swift\">self<\/span><span class=\"z-keyword z-operator z-custom z-postfix z-unary z-swift\">.<\/span>name <span class=\"z-keyword z-operator z-assignment z-swift\">=<\/span> <span class=\"z-support z-type z-swift\">String<\/span>(describing: type(of: <span class=\"z-keyword z-other z-statement z-swift\">self<\/span>))\n<\/span><span class=\"z-source z-swift\">    }\n<\/span><span class=\"z-source z-swift\">\n<\/span><span class=\"z-source z-swift\">    <span class=\"z-keyword z-other z-access-level-modifier z-swift\">public<\/span> <span class=\"z-storage z-type z-swift\">var<\/span> description: <span class=\"z-support z-type z-swift\">String<\/span> {\n<\/span><span class=\"z-source z-swift\"><span class=\"z-meta z-literal z-string z-swift\"><span class=\"z-string z-quoted z-double z-swift\">&quot;<\/span><span class=\"z-string z-quoted z-double z-swift\">&quot;<\/span><\/span><span class=\"z-meta z-literal z-string z-swift\"><span class=\"z-string z-quoted z-double z-swift\">&quot;<\/span>\n<\/span><\/span><span class=\"z-source z-swift\"><span class=\"z-meta z-literal z-string z-swift\"><span class=\"z-string z-quoted z-double z-swift\">E<\/span><span class=\"z-string z-quoted z-double z-swift\">v<\/span><span class=\"z-string z-quoted z-double z-swift\">e<\/span><span class=\"z-string z-quoted z-double z-swift\">n<\/span><span class=\"z-string z-quoted z-double z-swift\">t<\/span><span class=\"z-string z-quoted z-double z-swift\">:<\/span><span class=\"z-string z-quoted z-double z-swift\"> <\/span><span class=\"z-support z-punctuation z-expression z-begin z-swift\">\\(<\/span><span class=\"z-meta z-expression z-swift\">name<\/span><span class=\"z-support z-punctuation z-expression z-end z-swift\">)<\/span><span class=\"z-string z-quoted z-double z-swift\">;<\/span><span class=\"z-support z-punctuation z-expression z-begin z-swift\">\\(<\/span><span class=\"z-meta z-expression z-swift\">id<\/span><span class=\"z-support z-punctuation z-expression z-end z-swift\">)<\/span><span class=\"z-string z-quoted z-double z-swift\">;<\/span><span class=\"z-support z-punctuation z-expression z-begin z-swift\">\\(<\/span><span class=\"z-meta z-expression z-swift\">source<\/span><span class=\"z-support z-punctuation z-expression z-end z-swift\">)<\/span><span class=\"z-string z-quoted z-double z-swift\">;<\/span><span class=\"z-support z-punctuation z-expression z-begin z-swift\">\\(<\/span><span class=\"z-meta z-expression z-swift\">generationDate<\/span><span class=\"z-support z-punctuation z-expression z-end z-swift\">)<\/span>\n<\/span><\/span><span class=\"z-source z-swift\"><span class=\"z-meta z-literal z-string z-swift\"><span class=\"z-string z-quoted z-double z-swift\"> <\/span><span class=\"z-string z-quoted z-double z-swift\"> <\/span><span class=\"z-string z-quoted z-double z-swift\"> <\/span><span class=\"z-string z-quoted z-double z-swift\"> <\/span><span class=\"z-string z-quoted z-double z-swift\">P<\/span><span class=\"z-string z-quoted z-double z-swift\">a<\/span><span class=\"z-string z-quoted z-double z-swift\">y<\/span><span class=\"z-string z-quoted z-double z-swift\">l<\/span><span class=\"z-string z-quoted z-double z-swift\">o<\/span><span class=\"z-string z-quoted z-double z-swift\">a<\/span><span class=\"z-string z-quoted z-double z-swift\">d<\/span><span class=\"z-string z-quoted z-double z-swift\">:<\/span><span class=\"z-string z-quoted z-double z-swift\"> <\/span><span class=\"z-support z-punctuation z-expression z-begin z-swift\">\\(<\/span><span class=\"z-meta z-expression z-swift\"><span class=\"z-support z-type z-swift\">String<\/span>(describing: payload<\/span><span class=\"z-support z-punctuation z-expression z-end z-swift\">)<\/span><span class=\"z-string z-quoted z-double z-swift\">)<\/span>\n<\/span><\/span><span class=\"z-source z-swift\"><span class=\"z-meta z-literal z-string z-swift\"><span class=\"z-string z-quoted z-double z-swift\">&quot;<\/span><\/span><span class=\"z-meta z-literal z-string z-swift\"><span class=\"z-string z-quoted z-double z-swift\">&quot;<\/span><span class=\"z-string z-quoted z-double z-swift\">&quot;<\/span><\/span>\n<\/span><span class=\"z-source z-swift\">    }\n<\/span><span class=\"z-source z-swift\">}\n<\/span><\/code><\/pre>\n<p>And the EventBus:<\/p>\n<pre data-lang=\"swift\" class=\"language-swift z-code\"><code class=\"language-swift\" data-lang=\"swift\"><span class=\"z-source z-swift\"><span class=\"z-keyword z-other z-access-level-modifier z-swift\">public<\/span> <span class=\"z-storage z-type z-swift\">class<\/span> EventBus {\n<\/span><span class=\"z-source z-swift\">    <span class=\"z-keyword z-other z-access-level-modifier z-swift\">private<\/span> <span class=\"z-storage z-type z-swift\">let<\/span> sender <span class=\"z-keyword z-operator z-assignment z-swift\">=<\/span> PassthroughSubject<span class=\"z-keyword z-operator z-comparative z-swift\">&lt;<\/span>any EventProtocol, Never<span class=\"z-keyword z-operator z-comparative z-swift\">&gt;<\/span>()\n<\/span><span class=\"z-source z-swift\">    <span class=\"z-keyword z-other z-access-level-modifier z-swift\">public<\/span> <span class=\"z-storage z-type z-swift\">var<\/span> all: AnyPublisher<span class=\"z-keyword z-operator z-comparative z-swift\">&lt;<\/span>any EventProtocol, Never<span class=\"z-keyword z-operator z-comparative z-swift\">&gt;<\/span> {\n<\/span><span class=\"z-source z-swift\">        sender<span class=\"z-keyword z-operator z-custom z-postfix z-unary z-swift\">.<\/span>eraseToAnyPublisher()\n<\/span><span class=\"z-source z-swift\">    }\n<\/span><span class=\"z-source z-swift\">\n<\/span><span class=\"z-source z-swift\">    <span class=\"z-keyword z-other z-access-level-modifier z-swift\">public<\/span> <span class=\"z-meta z-function-declaration z-swift\"><span class=\"z-storage z-type z-function z-swift\">func<\/span> <span class=\"z-entity z-type z-function z-swift\">send<\/span><span class=\"z-meta z-generic-parameter-clause z-swift\"><span class=\"z-punctuation z-definition z-generic-parameter-clause z-begin z-swift\">&lt;<\/span>T: EventProtocol<span class=\"z-punctuation z-definition z-generic-parameter-clause z-end z-swift\">&gt;<\/span><\/span><span class=\"z-meta z-parameter-clause z-swift\"><span class=\"z-punctuation z-definition z-function-arguments z-begin z-swift\">(<\/span>_ event: T<span class=\"z-punctuation z-definition z-function-arguments z-end z-swift\">)<\/span><\/span> <span class=\"z-punctuation z-definition z-code-block z-begin z-swift\">{<\/span>\n<\/span><\/span><span class=\"z-source z-swift\"><span class=\"z-meta z-function-declaration z-swift\">        sender<span class=\"z-keyword z-operator z-custom z-postfix z-unary z-swift\">.<\/span>send(event)\n<\/span><\/span><span class=\"z-source z-swift\"><span class=\"z-meta z-function-declaration z-swift\">    <span class=\"z-punctuation z-definition z-code-block z-end z-swift\">}<\/span><\/span>\n<\/span><span class=\"z-source z-swift\">\n<\/span><span class=\"z-source z-swift\">    <span class=\"z-keyword z-other z-access-level-modifier z-swift\">public<\/span> <span class=\"z-meta z-function-declaration z-swift\"><span class=\"z-storage z-type z-function z-swift\">func<\/span> <span class=\"z-entity z-type z-function z-swift\">receive<\/span><span class=\"z-meta z-generic-parameter-clause z-swift\"><span class=\"z-punctuation z-definition z-generic-parameter-clause z-begin z-swift\">&lt;<\/span>T: EventProtocol<span class=\"z-punctuation z-definition z-generic-parameter-clause z-end z-swift\">&gt;<\/span><\/span><span class=\"z-meta z-parameter-clause z-swift\"><span class=\"z-punctuation z-definition z-function-arguments z-begin z-swift\">(<\/span>_ receive: T<span class=\"z-keyword z-operator z-custom z-postfix z-unary z-swift\">.<\/span><span class=\"z-keyword z-other z-statement z-swift\">Type<\/span><span class=\"z-punctuation z-definition z-function-arguments z-end z-swift\">)<\/span><\/span> <span class=\"z-meta z-function-result z-swift\"><span class=\"z-keyword z-operator z-function-result z-swift\">-&gt;<\/span> AnyPublisher&lt;T, Never&gt; <\/span><span class=\"z-punctuation z-definition z-code-block z-begin z-swift\">{<\/span>\n<\/span><\/span><span class=\"z-source z-swift\"><span class=\"z-meta z-function-declaration z-swift\">        all\n<\/span><\/span><span class=\"z-source z-swift\"><span class=\"z-meta z-function-declaration z-swift\">            <span class=\"z-keyword z-operator z-custom z-prefix z-unary z-swift\">.<\/span>compactMap { $<span class=\"z-constant z-numeric z-integer z-decimal z-swift\">0<\/span> <span class=\"z-keyword z-operator z-type-casting z-swift\">as?<\/span> T <span class=\"z-punctuation z-definition z-code-block z-end z-swift\">}<\/span><\/span>\n<\/span><span class=\"z-source z-swift\">            <span class=\"z-keyword z-operator z-custom z-prefix z-unary z-swift\">.<\/span>eraseToAnyPublisher()\n<\/span><span class=\"z-source z-swift\">    }\n<\/span><span class=\"z-source z-swift\">}\n<\/span><\/code><\/pre>\n<p>This naive design is intentionally minimal. It can be extended to include filtering or a <code>receiveOnMain<\/code> convenience to simplify receiving events on the main thread. Because this uses Combine, events can be zipped, merged, and otherwise composed with the framework\u2019s operators.<\/p>\n<h2 id=\"integration-in-the-app\">Integration in the app<\/h2>\n<p>I\u2019m designing the app so that all parts communicate via a single event bus. Making EventBus a singleton is appealing, but singletons complicate unit testing\u2014especially when tests run in parallel. One test can send an event that another test receives, causing unexpected behavior.<\/p>\n<p>To mitigate this, use dependency injection to provide the EventBus instance to components that need it. This allows creating separate bus instances per test.<\/p>\n<p>However, this introduces \u201cconstructor pollution\u201d: every component that uses the bus must accept it in its initializer. This is a common trade-off discussed in detail in the Dependency Injection book.<\/p>\n<p>I integrate <code>eventBus<\/code> via the SwiftUI environment:<\/p>\n<pre class=\"z-code\"><code><span class=\"z-text z-plain\">extension EnvironmentValues {\n<\/span><span class=\"z-text z-plain\">    var eventBus: EventBus {\n<\/span><span class=\"z-text z-plain\">        get { self[EventBusKey.self] }\n<\/span><span class=\"z-text z-plain\">        set { self[EventBusKey.self] = newValue }\n<\/span><span class=\"z-text z-plain\">    }\n<\/span><span class=\"z-text z-plain\">}\n<\/span><span class=\"z-text z-plain\">\n<\/span><span class=\"z-text z-plain\">struct EventBusKey: EnvironmentKey {\n<\/span><span class=\"z-text z-plain\">    public static let defaultValue: EventBus = .shared\n<\/span><span class=\"z-text z-plain\">}\n<\/span><\/code><\/pre>\n<h3 id=\"example-using-eventbus-in-a-swiftui-view\">Example: Using EventBus in a SwiftUI view<\/h3>\n<p>Inject from the environment, subscribe with onReceive, and send from UI actions.<\/p>\n<pre data-lang=\"swift\" class=\"language-swift z-code\"><code class=\"language-swift\" data-lang=\"swift\"><span class=\"z-source z-swift\"><span class=\"z-meta z-import z-swift\"><span class=\"z-keyword z-other z-import z-swift\">import<\/span> <span class=\"z-support z-type z-module z-import z-swift\">SwiftUI<\/span><\/span>\n<\/span><span class=\"z-source z-swift\">\n<\/span><span class=\"z-source z-swift\"><span class=\"z-storage z-type z-swift\">struct<\/span> PlaylistView: View {\n<\/span><span class=\"z-source z-swift\">    <span class=\"z-storage z-modifier z-attribute z-swift\"><span class=\"z-punctuation z-definition z-attribute z-swift\">@<\/span><span class=\"z-punctuation z-definition z-attribute-arguments z-begin z-swift\">Environment<\/span><\/span>(<span class=\"z-meta z-attribute z-arguments z-swift\">\\<span class=\"z-keyword z-operator z-custom z-postfix z-unary z-swift\">.<\/span>eventBus<\/span><span class=\"z-punctuation z-definition z-attribute-arguments z-end z-swift\">)<\/span> <span class=\"z-keyword z-other z-access-level-modifier z-swift\">private<\/span> <span class=\"z-storage z-type z-swift\">var<\/span> eventBus\n<\/span><span class=\"z-source z-swift\">    <span class=\"z-storage z-modifier z-attribute z-swift\"><span class=\"z-punctuation z-definition z-attribute z-swift\">@<\/span>State<\/span> <span class=\"z-keyword z-other z-access-level-modifier z-swift\">private<\/span> <span class=\"z-storage z-type z-swift\">var<\/span> shuffledSongs: [Song] <span class=\"z-keyword z-operator z-assignment z-swift\">=<\/span> [] <span class=\"z-comment z-line z-double-slash z-swift\"><span class=\"z-punctuation z-definition z-comment z-line z-double-slash z-swift\">\/\/<\/span> Assuming `Song: Identifiable`<\/span>\n<\/span><span class=\"z-source z-swift\">\n<\/span><span class=\"z-source z-swift\">    <span class=\"z-storage z-type z-swift\">var<\/span> body: some View {\n<\/span><span class=\"z-source z-swift\">        List(shuffledSongs) { song <span class=\"z-keyword z-control z-loop z-swift\">in<\/span>\n<\/span><span class=\"z-source z-swift\">            Text(song<span class=\"z-keyword z-operator z-custom z-postfix z-unary z-swift\">.<\/span>title)\n<\/span><span class=\"z-source z-swift\">        }\n<\/span><span class=\"z-source z-swift\">        <span class=\"z-keyword z-operator z-custom z-prefix z-unary z-swift\">.<\/span>toolbar {\n<\/span><span class=\"z-source z-swift\">            Button(<span class=\"z-meta z-literal z-string z-swift\"><span class=\"z-string z-quoted z-double z-swift\">&quot;<\/span><span class=\"z-string z-quoted z-double z-swift\">S<\/span><span class=\"z-string z-quoted z-double z-swift\">h<\/span><span class=\"z-string z-quoted z-double z-swift\">u<\/span><span class=\"z-string z-quoted z-double z-swift\">f<\/span><span class=\"z-string z-quoted z-double z-swift\">f<\/span><span class=\"z-string z-quoted z-double z-swift\">l<\/span><span class=\"z-string z-quoted z-double z-swift\">e<\/span><span class=\"z-string z-quoted z-double z-swift\">&quot;<\/span><\/span>) {\n<\/span><span class=\"z-source z-swift\">                eventBus<span class=\"z-keyword z-operator z-custom z-postfix z-unary z-swift\">.<\/span>send(SongsShuffleRequested())\n<\/span><span class=\"z-source z-swift\">            }\n<\/span><span class=\"z-source z-swift\">        }\n<\/span><span class=\"z-source z-swift\">    }\n<\/span><span class=\"z-source z-swift\">}\n<\/span><\/code><\/pre>\n<h2 id=\"thread-safety\">Thread safety<\/h2>\n<p>Events can be produced from multiple threads. Without explicit scheduling, each value is delivered to subscribers on the same thread that called <code>send<\/code>. Combine then guarantees, per subscription, that the subscriber\u2019s <code>receive<\/code>\/handling callback is invoked sequentially (no concurrent reentry) and in order. Across different subscribers (or after <code>receive(on:)<\/code>), callbacks may run in parallel on their respective schedulers.<\/p>\n<p>Key points:<\/p>\n<ul>\n<li>Sends: Multiple producers can call <code>send<\/code> from different threads. If you need global ordering or single-writer semantics, serialize calls to <code>send<\/code> (e.g., via a serial queue\/actor).<\/li>\n<li>Delivery thread: Use <code>receive(on:)<\/code> to hop to a specific scheduler (e.g., main) for UI work. Without it, handling runs on the sending thread.<\/li>\n<li>Per-subscriber sequencing: Each subscriber\u2019s handling is serial and ordered; different subscribers can handle events concurrently.<\/li>\n<\/ul>\n<p>Visualizing parallel production with per-subscriber sequential handling:<\/p>\n<pre class=\"z-code\"><code><span class=\"z-text z-plain\">Sending (producers)\n<\/span><span class=\"z-text z-plain\">[thread A] - a ----------- e -\n<\/span><span class=\"z-text z-plain\">[thread B] ---- b -\n<\/span><span class=\"z-text z-plain\">[thread C] -------- c --- d -\n<\/span><span class=\"z-text z-plain\">\n<\/span><span class=\"z-text z-plain\">Delivery (subscribers)\n<\/span><span class=\"z-text z-plain\">Subscriber 1 (Main) [serial]: a -&gt; c -&gt; e\n<\/span><span class=\"z-text z-plain\">Subscriber 2 (BG)   [serial]: b -&gt; d\n<\/span><span class=\"z-text z-plain\">\/\/ Note: Subscriber 1 and 2 can run in parallel on different schedulers,\n<\/span><span class=\"z-text z-plain\">\/\/ but each subscriber&#39;s callback runs one event at a time, in order.\n<\/span><\/code><\/pre>\n<p>Practical guidance:<\/p>\n<ul>\n<li>UI safety: <code>eventBus.receive(Event.self).receive(on: DispatchQueue.main)<\/code> before updating views.<\/li>\n<li>Shared mutable state: confine to a serial queue\/actor or hop to one with <code>receive(on:)<\/code>.<\/li>\n<li>If strict global ordering is required, ensure <code>send<\/code> is funneled through a single serialization point.<\/li>\n<\/ul>\n<h2 id=\"notificationcenter\">NotificationCenter<\/h2>\n<p>With the new API in iOS 26, it\u2019s worth considering the updated <code>NotificationCenter<\/code>. I plan to experiment with whether it can serve as an event bus.<\/p>\n<aside class=\"alert\"><p>If you have used the Objective\u2011C\u2013based <code>NotificationCenter<\/code> to broadcast notifications across an iOS app, you should know that, starting with iOS 26, Apple introduced a new API to send and receive notifications in a <a href=\"https:\/\/developer.apple.com\/documentation\/foundation\/notificationcenter\/post(_:)-19s7b\">type-safe manner<\/a>. It also adopts more event-driven naming, such as <code>Message<\/code> instead of <code>Notification<\/code>.<\/p>\n<\/aside>"},{"title":"Event driven navigation pattern in iOS","pubDate":"Mon, 17 Mar 2025 00:00:00 +0000","author":"Ion Ostafi","link":"https:\/\/ionostafi.com\/blog\/ios-event-driven-navigation\/","guid":"https:\/\/ionostafi.com\/blog\/ios-event-driven-navigation\/","description":"<p><img src=\"https:\/\/ionostafi.com\/blog\/ios-event-driven-navigation\/.\/event_driven_mvvm_navigation.png\" alt=\"event_driven_mvvm_navigation\" \/><\/p>\n<h2 id=\"who-this-article-is-for\">Who this article is for<\/h2>\n<p>This article is for iOS developers exploring app navigation patterns. If you\u2019ve been wondering whether SwiftUI is suitable for navigation or if you should stick with UIKit, this article will provide valuable insights and a solution that worked for me.<\/p>\n<p>It is also aimed at developers who want to see an example of SwiftUI-only navigation for iOS. The existing solution can be adapted to a non-Event-Driven Architecture (EDA) by replacing events with method calls to a router object, such as <strong>router.navigate(..)<\/strong>. The key difference is that instructing the router where to navigate is imperative, while sending an event is reactive.<\/p>\n<h2 id=\"introduction\">Introduction<\/h2>\n<p>Based on my <a href=\"..\/ios-event-driven-architecture\">current work<\/a>, I am developing app navigation using an Event-Driven Architecture (EDA).<\/p>\n<p>In EDA theory, events are categorized into the following types:<\/p>\n<ul>\n<li><strong>Commands<\/strong>: Events that trigger an action.<\/li>\n<li><strong>Events<\/strong>: Events that notify about a change.<\/li>\n<li><strong>Documents<\/strong>: Events that store data.<\/li>\n<li><strong>Queries<\/strong>: Events that request data.<\/li>\n<\/ul>\n<p>For the iOS app, I have defined the following events that can influence navigation. Note that queries and documents are not utilized in the navigation layer of the app.<\/p>\n<ul>\n<li><strong>User Commands<\/strong>: Actions initiated by the user, such as logging in, logging out, or playing a song.<\/li>\n<li><strong>System Events<\/strong>: Events triggered by the system, such as the system finishing its launch or receiving a deep link.<\/li>\n<li><strong>Application Events<\/strong>: Events triggered by application services, such as shuffling songs from a playlist, authorizing a service, or deauthorizing a service. Application events can be responses to user commands or system events.<\/li>\n<\/ul>\n<h2 id=\"code\">Code<\/h2>\n<p>Before delving into the details, here is the final code for a simple SwiftUI coordinator\u2014a View that manages navigation within the app.<\/p>\n<pre data-lang=\"swift\" class=\"language-swift z-code\"><code class=\"language-swift\" data-lang=\"swift\"><span class=\"z-source z-swift\"><span class=\"z-storage z-type z-swift\">struct<\/span> MainCoordinator: View {\n<\/span><span class=\"z-source z-swift\">    <span class=\"z-storage z-type z-swift\">let<\/span> compositor: CompositionRoot\n<\/span><span class=\"z-source z-swift\">    <span class=\"z-storage z-modifier z-attribute z-swift\"><span class=\"z-punctuation z-definition z-attribute z-swift\">@<\/span>ObservedObject<\/span> <span class=\"z-storage z-type z-swift\">var<\/span> viewModel: NavigationViewModel\n<\/span><span class=\"z-source z-swift\">\n<\/span><span class=\"z-source z-swift\">    <span class=\"z-storage z-type z-swift\">var<\/span> body: some View {\n<\/span><span class=\"z-source z-swift\">        ZStack {\n<\/span><span class=\"z-source z-swift\">            <span class=\"z-keyword z-control z-switch z-swift\">switch<\/span> viewModel<span class=\"z-keyword z-operator z-custom z-postfix z-unary z-swift\">.<\/span>root {\n<\/span><span class=\"z-source z-swift\">            <span class=\"z-keyword z-control z-switch z-swift\">case<\/span> <span class=\"z-keyword z-operator z-custom z-prefix z-unary z-swift\">.<\/span>launch:\n<\/span><span class=\"z-source z-swift\">                LaunchView()\n<\/span><span class=\"z-source z-swift\">            <span class=\"z-keyword z-control z-switch z-swift\">case<\/span> <span class=\"z-keyword z-operator z-custom z-prefix z-unary z-swift\">.<\/span>serviceSelection:\n<\/span><span class=\"z-source z-swift\">                ServiceSelectionView()\n<\/span><span class=\"z-source z-swift\">            <span class=\"z-keyword z-control z-switch z-swift\">case<\/span> <span class=\"z-keyword z-operator z-custom z-prefix z-unary z-swift\">.<\/span>playlistSelection:\n<\/span><span class=\"z-source z-swift\">                NavigationStack {\n<\/span><span class=\"z-source z-swift\">                    ChoosePlaylistView()\n<\/span><span class=\"z-source z-swift\">                        <span class=\"z-keyword z-operator z-custom z-prefix z-unary z-swift\">.<\/span>environmentObject(compositor<span class=\"z-keyword z-operator z-custom z-postfix z-unary z-swift\">.<\/span>choosePlaylistViewModel)\n<\/span><span class=\"z-source z-swift\">                        <span class=\"z-keyword z-operator z-custom z-prefix z-unary z-swift\">.<\/span>navigationDestination(\n<\/span><span class=\"z-source z-swift\">                            isPresented: $viewModel<span class=\"z-keyword z-operator z-custom z-postfix z-unary z-swift\">.<\/span>isFocusPlaylistPresented,\n<\/span><span class=\"z-source z-swift\">                            destination: {\n<\/span><span class=\"z-source z-swift\">                                GeneratedPlaylistView()\n<\/span><span class=\"z-source z-swift\">                                    <span class=\"z-keyword z-operator z-custom z-prefix z-unary z-swift\">.<\/span>environmentObject(compositor<span class=\"z-keyword z-operator z-custom z-postfix z-unary z-swift\">.<\/span>generatedPlaylisViewModel)\n<\/span><span class=\"z-source z-swift\">                            }\n<\/span><span class=\"z-source z-swift\">                        )\n<\/span><span class=\"z-source z-swift\">                }\n<\/span><span class=\"z-source z-swift\">                <span class=\"z-keyword z-operator z-custom z-prefix z-unary z-swift\">.<\/span>sheet(isPresented: $viewModel<span class=\"z-keyword z-operator z-custom z-postfix z-unary z-swift\">.<\/span>isSpotifyDeviceActivationPresented) {\n<\/span><span class=\"z-source z-swift\">                    DeviceActivationView()\n<\/span><span class=\"z-source z-swift\">                        <span class=\"z-keyword z-operator z-custom z-prefix z-unary z-swift\">.<\/span>environmentObject(compositor<span class=\"z-keyword z-operator z-custom z-postfix z-unary z-swift\">.<\/span>deviceActivationViewModel)\n<\/span><span class=\"z-source z-swift\">                        <span class=\"z-keyword z-operator z-custom z-prefix z-unary z-swift\">.<\/span>presentationDetents([<span class=\"z-keyword z-operator z-custom z-prefix z-unary z-swift\">.<\/span>medium])\n<\/span><span class=\"z-source z-swift\">                        <span class=\"z-keyword z-operator z-custom z-prefix z-unary z-swift\">.<\/span>presentationDragIndicator(<span class=\"z-keyword z-operator z-custom z-prefix z-unary z-swift\">.<\/span>visible)\n<\/span><span class=\"z-source z-swift\">                }\n<\/span><span class=\"z-source z-swift\">            }\n<\/span><span class=\"z-source z-swift\">            ErrorNotificationView()\n<\/span><span class=\"z-source z-swift\">                <span class=\"z-keyword z-operator z-custom z-prefix z-unary z-swift\">.<\/span>environmentObject(compositor<span class=\"z-keyword z-operator z-custom z-postfix z-unary z-swift\">.<\/span>errorViewModel)\n<\/span><span class=\"z-source z-swift\">        }\n<\/span><span class=\"z-source z-swift\">    }\n<\/span><span class=\"z-source z-swift\">}\n<\/span><\/code><\/pre>\n<p>The list of all commands and events that are listened by the NavigationViewModel<\/p>\n<pre data-lang=\"swift\" class=\"language-swift z-code\"><code class=\"language-swift\" data-lang=\"swift\"><span class=\"z-source z-swift\">DomainEvent<span class=\"z-keyword z-operator z-custom z-postfix z-unary z-swift\">.<\/span>SpotifyAuthorizationUpdated\n<\/span><span class=\"z-source z-swift\">DomainEvent<span class=\"z-keyword z-operator z-custom z-postfix z-unary z-swift\">.<\/span>LaunchFinished\n<\/span><span class=\"z-source z-swift\">DomainEvent<span class=\"z-keyword z-operator z-custom z-postfix z-unary z-swift\">.<\/span>SpotifyAuthURLGenerated\n<\/span><span class=\"z-source z-swift\">Command<span class=\"z-keyword z-operator z-custom z-postfix z-unary z-swift\">.<\/span>PlaylistSelected\n<\/span><span class=\"z-source z-swift\">Command<span class=\"z-keyword z-operator z-custom z-postfix z-unary z-swift\">.<\/span>OpenAnotherAppRequested\n<\/span><span class=\"z-source z-swift\">Command<span class=\"z-keyword z-operator z-custom z-postfix z-unary z-swift\">.<\/span>DidRequestOpenPlaylistOnSpotify\n<\/span><span class=\"z-source z-swift\">Command<span class=\"z-keyword z-operator z-custom z-postfix z-unary z-swift\">.<\/span>PlayOnSpotifyRequested\n<\/span><span class=\"z-source z-swift\">DomainEvent<span class=\"z-keyword z-operator z-custom z-postfix z-unary z-swift\">.<\/span>SpotifyPremiumOnlyActionAttempted\n<\/span><\/code><\/pre>\n<h2 id=\"navigation-layer\">Navigation layer<\/h2>\n<p>In an N-tier architecture, the navigation layer is the topmost layer of the application. It is responsible for switching between views and serves as the entry point of the app, being the first layer initialized when the app starts.<\/p>\n<p>The tiers are structured as follows:<\/p>\n<ol>\n<li><strong>Navigation Layer<\/strong>: The top layer of the app, responsible for switching between views.<\/li>\n<li><strong>Presentation Layer<\/strong>: Contains the views and view models.<\/li>\n<li><strong>Domain Layer<\/strong>: Contains the service classes and domain models.<\/li>\n<li><strong>Data Layer<\/strong>: Contains the repositories.<\/li>\n<\/ol>\n<p>Since the navigation layer is responsible for creating views, it has knowledge of all the layers below it. It creates the views, listens to domain events and commands, and decides what to present next to the user.<\/p>\n<p>By having the <strong>NavigationViewModel<\/strong> listen to application events, I can handle events such as <strong>SpotifyAuthorizationUpdated<\/strong> and navigate back to a service selection screen where the user will need to reauthorize the service. Additionally, an error message will be displayed. This navigation logic resides in the navigation layer, not in the presentation layer (View or ViewModel).<\/p>\n<p>The navigation layer is a cross-cutting concern that unifies different domains of the app. It is the glue that holds the app together.<\/p>\n<h2 id=\"modeling-the-navigation-state\">Modeling the navigation state<\/h2>\n<p>The <strong>NavigationViewModel<\/strong> can be modeled in any way that fits better for each application separately. If I have to display only a stack of views, then it will contain an array of data. If the app has more complicated navigation paths, then the ViewModel will look more complicated.<\/p>\n<p>For simplicity, I used an <strong>enum<\/strong> to define the possible <strong>root views<\/strong> and a list of <strong>flags<\/strong> to model <strong>which screen<\/strong> is displayed at the moment.<\/p>\n<pre data-lang=\"swift\" class=\"language-swift z-code\"><code class=\"language-swift\" data-lang=\"swift\"><span class=\"z-source z-swift\"><span class=\"z-storage z-type z-swift\">class<\/span> NavigationViewModel: ObservableObject {\n<\/span><span class=\"z-source z-swift\">    <span class=\"z-storage z-modifier z-attribute z-swift\"><span class=\"z-punctuation z-definition z-attribute z-swift\">@<\/span>Published<\/span> <span class=\"z-storage z-modifier z-attribute z-swift\"><span class=\"z-punctuation z-definition z-attribute z-swift\">@<\/span>MainActor<\/span> <span class=\"z-storage z-type z-swift\">var<\/span> root: RootView <span class=\"z-keyword z-operator z-assignment z-swift\">=<\/span> <span class=\"z-keyword z-operator z-custom z-prefix z-unary z-swift\">.<\/span>launch\n<\/span><span class=\"z-source z-swift\">    <span class=\"z-storage z-modifier z-attribute z-swift\"><span class=\"z-punctuation z-definition z-attribute z-swift\">@<\/span>Published<\/span> <span class=\"z-storage z-modifier z-attribute z-swift\"><span class=\"z-punctuation z-definition z-attribute z-swift\">@<\/span>MainActor<\/span> <span class=\"z-storage z-type z-swift\">var<\/span> isFocusPlaylistPresented: <span class=\"z-support z-type z-swift\">Bool<\/span> <span class=\"z-keyword z-operator z-assignment z-swift\">=<\/span> <span class=\"z-keyword z-constant z-boolean z-swift\">false<\/span>\n<\/span><span class=\"z-source z-swift\">    <span class=\"z-storage z-modifier z-attribute z-swift\"><span class=\"z-punctuation z-definition z-attribute z-swift\">@<\/span>Published<\/span> <span class=\"z-storage z-modifier z-attribute z-swift\"><span class=\"z-punctuation z-definition z-attribute z-swift\">@<\/span>MainActor<\/span> <span class=\"z-storage z-type z-swift\">var<\/span> isSpotifyDeviceActivationPresented: <span class=\"z-support z-type z-swift\">Bool<\/span> <span class=\"z-keyword z-operator z-assignment z-swift\">=<\/span> <span class=\"z-keyword z-constant z-boolean z-swift\">false<\/span>\n<\/span><\/code><\/pre>\n<p>With this approach, it leaves the <strong>Coordinator<\/strong> implementation to decide how to display each flag, where each flag can also be a bi-directional <strong>Binding<\/strong> and used in SwiftUI as a flag to display a sheet. Closing the sheet from the SwiftUI side will also update the NavigationViewModel. But  I have to <strong>maintain<\/strong> the flags and make sure to turn them on\/off if I have to display a single screen at a time.<\/p>\n<aside class=\"alert\"><p><strong>NavigationViewModel<\/strong> is the <strong>single source of truth for the navigation state of the app<\/strong>. It is testable, it is simple, and it is easy to understand.<\/p>\n<\/aside>\n<hr \/>\n<h2 id=\"sending-parameters-between-screen\">Sending parameters between screen<\/h2>\n<p><em>The best code is the one that doesn\u2019t exist.<\/em> \u2014 With this principle in mind, I prefer to avoid passing parameters between screens whenever possible.<\/p>\n<pre data-lang=\"swift\" class=\"language-swift z-code\"><code class=\"language-swift\" data-lang=\"swift\"><span class=\"z-source z-swift\"><span class=\"z-keyword z-control z-switch z-swift\">case<\/span> <span class=\"z-keyword z-operator z-custom z-prefix z-unary z-swift\">.<\/span>playlistSelection:\n<\/span><span class=\"z-source z-swift\">    NavigationStack {\n<\/span><span class=\"z-source z-swift\">        ChoosePlaylistView()\n<\/span><span class=\"z-source z-swift\">            <span class=\"z-keyword z-operator z-custom z-prefix z-unary z-swift\">.<\/span>environmentObject(compositor<span class=\"z-keyword z-operator z-custom z-postfix z-unary z-swift\">.<\/span>choosePlaylistViewModel)\n<\/span><span class=\"z-source z-swift\">            <span class=\"z-keyword z-operator z-custom z-prefix z-unary z-swift\">.<\/span>navigationDestination(\n<\/span><span class=\"z-source z-swift\">                isPresented: $viewModel<span class=\"z-keyword z-operator z-custom z-postfix z-unary z-swift\">.<\/span>isFocusPlaylistPresented,\n<\/span><span class=\"z-source z-swift\">                destination: {\n<\/span><span class=\"z-source z-swift\">                    GeneratedPlaylistView()\n<\/span><span class=\"z-source z-swift\">                        <span class=\"z-keyword z-operator z-custom z-prefix z-unary z-swift\">.<\/span>environmentObject(compositor<span class=\"z-keyword z-operator z-custom z-postfix z-unary z-swift\">.<\/span>generatedPlaylisViewModel)\n<\/span><span class=\"z-source z-swift\">                }\n<\/span><span class=\"z-source z-swift\">            )\n<\/span><span class=\"z-source z-swift\">    }\n<\/span><\/code><\/pre>\n<p>The reader can note that the <strong>ChoosePlaylistView<\/strong> and <strong>GeneratedPlaylistView<\/strong> do not send data between them.<\/p>\n<p>I challenged myself - design communication between screens that <strong>doesn\u2019t require sending any data from one View to another<\/strong>.<\/p>\n<p>This is hard to think about because the usual thinking of iOS developers is not even near to such an idea. But I think that arguments couple the Views and make it harder to experiment with different navigation patterns or to even switch to different navigation flows.<\/p>\n<p>Screens communicate between them by sharing the same object that provides data. Usually a repository class form the data layer or same service object. But because this is <strong>event driven architecture<\/strong> - each ViewModel will get data from the <strong>EventBus<\/strong> in a reactive way:<\/p>\n<ol>\n<li>ChoosePlaylistView tells EventBus - user selected a playlist by id<\/li>\n<li>MusicService receives the event and fetches the playlist songs<\/li>\n<li>NavigationModel receives the event and changes the state to display the GeneratedPlaylistView<\/li>\n<li>GeneratedPlaylistView listens to the EventBus for the playlist data<\/li>\n<li>MusicService sends the generated playlist to the EventBus<\/li>\n<li>GeneratedPlaylistView receives the playlist and displays it<\/li>\n<\/ol>\n<p>MusicService is responsible for providing data by id. It is using objects implementing repository pattern to cache data in memory or on a local database.<\/p>\n<p>The reader can note that the <strong>ChoosePlaylistView<\/strong> and <strong>GeneratedPlaylistView<\/strong> do not send data between them.<\/p>\n<p>I challenged myself to design communication between screens that <strong>doesn\u2019t require sending any data from one View to another<\/strong>.<\/p>\n<p>This approach is unconventional for many iOS developers, as it deviates from the typical practice of passing parameters between views. However, I believe that passing arguments couples the views and makes it harder to experiment with different navigation patterns or switch to different navigation flows.<\/p>\n<p>Screens communicate by sharing the same object that provides data, typically a repository class from the data layer or a service object. In this <strong>event-driven architecture<\/strong>, each ViewModel retrieves data from the <strong>EventBus<\/strong> in a reactive manner:<\/p>\n<ol>\n<li><strong>ChoosePlaylistView<\/strong> notifies the EventBus that the user has selected a playlist by its ID.<\/li>\n<li><strong>MusicService<\/strong> receives the event and fetches the playlist songs.<\/li>\n<li><strong>NavigationModel<\/strong> receives the event and updates the state to display the <strong>GeneratedPlaylistView<\/strong>.<\/li>\n<li><strong>GeneratedPlaylistView<\/strong> listens to the EventBus for the playlist data.<\/li>\n<li><strong>MusicService<\/strong> sends the generated playlist to the EventBus.<\/li>\n<li><strong>GeneratedPlaylistView<\/strong> receives the playlist and displays it.<\/li>\n<\/ol>\n<p>The <strong>MusicService<\/strong> is responsible for providing data by ID. It uses objects implementing the repository pattern to cache data in memory or a local database.<\/p>\n<p>This design ensures that views remain decoupled, making it easier to experiment with different navigation patterns and flows.<\/p>\n<hr \/>\n<h2 id=\"displaying-a-modal-view-on-top-of-any-screen\">Displaying a modal view on top of any screen<\/h2>\n<pre data-lang=\"swift\" class=\"language-swift z-code\"><code class=\"language-swift\" data-lang=\"swift\"><span class=\"z-source z-swift\"><span class=\"z-keyword z-operator z-custom z-postfix z-unary z-swift\">.<\/span>sheet(isPresented: $viewModel<span class=\"z-keyword z-operator z-custom z-postfix z-unary z-swift\">.<\/span>isSpotifyDeviceActivationPresented) {\n<\/span><span class=\"z-source z-swift\">    DeviceActivationView()\n<\/span><span class=\"z-source z-swift\">        <span class=\"z-keyword z-operator z-custom z-prefix z-unary z-swift\">.<\/span>environmentObject(compositor<span class=\"z-keyword z-operator z-custom z-postfix z-unary z-swift\">.<\/span>deviceActivationViewModel)\n<\/span><span class=\"z-source z-swift\">        <span class=\"z-keyword z-operator z-custom z-prefix z-unary z-swift\">.<\/span>presentationDetents([<span class=\"z-keyword z-operator z-custom z-prefix z-unary z-swift\">.<\/span>medium])\n<\/span><span class=\"z-source z-swift\">        <span class=\"z-keyword z-operator z-custom z-prefix z-unary z-swift\">.<\/span>presentationDragIndicator(<span class=\"z-keyword z-operator z-custom z-prefix z-unary z-swift\">.<\/span>visible)\n<\/span><span class=\"z-source z-swift\">}\n<\/span><\/code><\/pre>\n<p>The <strong>DeviceActivationView<\/strong> is a view that is displayed as a sheet. The flag for controlling its presentation is stored in the NavigationViewModel and it is sent to the <code>.sheet<\/code> function as a <strong>Binding<\/strong>. When the user closes the sheet, the flag is set to false by the SwiftUI and the sheet is dismissed.<\/p>\n<p>The <strong>Coordinator<\/strong>, being a SwiftUI view, controls how a <strong>View<\/strong> is displayed. It can manage the presentation of views in various forms, such as:<\/p>\n<ul>\n<li>Sheet<\/li>\n<li>Alert<\/li>\n<li>Navigation stack<\/li>\n<li>Full-screen view<\/li>\n<\/ul>\n<hr \/>\n<h2 id=\"displaying-an-error-banner-on-top-of-any-view\">Displaying an error banner on top of any view<\/h2>\n<pre data-lang=\"swift\" class=\"language-swift z-code\"><code class=\"language-swift\" data-lang=\"swift\"><span class=\"z-source z-swift\"><span class=\"z-storage z-type z-swift\">var<\/span> body: some View {\n<\/span><span class=\"z-source z-swift\">    ZStack {\n<\/span><span class=\"z-source z-swift\">        <span class=\"z-comment z-line z-double-slash z-swift\"><span class=\"z-punctuation z-definition z-comment z-line z-double-slash z-swift\">\/\/<\/span> other views<\/span>\n<\/span><span class=\"z-source z-swift\">        ErrorNotificationView()\n<\/span><span class=\"z-source z-swift\">            <span class=\"z-keyword z-operator z-custom z-prefix z-unary z-swift\">.<\/span>environmentObject(compositor<span class=\"z-keyword z-operator z-custom z-postfix z-unary z-swift\">.<\/span>errorViewModel)\n<\/span><span class=\"z-source z-swift\">    }\n<\/span><span class=\"z-source z-swift\">}\n<\/span><\/code><\/pre>\n<p><strong>ErrorNotificationView<\/strong> is a view that hides\/displays itself based on the state of the <strong>ErrorViewModel<\/strong>, which listens to the event bus for <strong>ApplicationError<\/strong> events. The <strong>ErrorNotificationView<\/strong> is a global view that is displayed on top of the navigation stack, so the user can see the error message no matter where they are in the app.<\/p>\n<p>Any service in the app can send an <strong>ApplicationError<\/strong> event to the event bus, and the <strong>ErrorViewModel<\/strong> will display the error message to the user. <strong>ErrorNotificationView<\/strong> handles the logic of auto-hiding based on a timer.<\/p>\n<hr \/>\n<h2 id=\"visualizing-the-navigation-events\">Visualizing the navigation events<\/h2>\n<p>The <strong>arrows<\/strong> represent the events that can change the state of the app. In code, an event triggered by the user is a <strong>Command<\/strong> and it is sent to the <strong>eventBus<\/strong> directly from the <strong>View<\/strong> that handles the action. Sending commands directly from the Views is a personal decision and another experiment in order to reduce the complexity of the app. Usually, the view will call a method from the <strong>ViewModel<\/strong> and the <strong>ViewModel<\/strong> will send the command to the <strong>eventBus<\/strong>. This is a more common approach, but I think if the view only sends commands, then I can have less boilerplate code in the <strong>ViewModel<\/strong>.<\/p>\n<p><img src=\"https:\/\/ionostafi.com\/blog\/ios-event-driven-navigation\/.\/navigation_state.png\" alt=\"Sequence diagram\" \/><\/p>\n<hr \/>\n<h2 id=\"example-of-sending-commands-from-the-view\">Example of sending commands from the view<\/h2>\n<pre data-lang=\"swift\" class=\"language-swift z-code\"><code class=\"language-swift\" data-lang=\"swift\"><span class=\"z-source z-swift\"><span class=\"z-comment z-line z-double-slash z-swift\"><span class=\"z-punctuation z-definition z-comment z-line z-double-slash z-swift\">\/\/<\/span> file:ConnectSpotifyButton.swift<\/span>\n<\/span><span class=\"z-source z-swift\">Button(action: {\n<\/span><span class=\"z-source z-swift\">    eventBus<span class=\"z-keyword z-operator z-custom z-postfix z-unary z-swift\">.<\/span>send(Command<span class=\"z-keyword z-operator z-custom z-postfix z-unary z-swift\">.<\/span>SpotifyAuthorizationRequested())\n<\/span><span class=\"z-source z-swift\">}\n<\/span><span class=\"z-source z-swift\">\n<\/span><span class=\"z-source z-swift\"><span class=\"z-comment z-line z-double-slash z-swift\"><span class=\"z-punctuation z-definition z-comment z-line z-double-slash z-swift\">\/\/<\/span> file:PlaylistsGrid.swift<\/span>\n<\/span><span class=\"z-source z-swift\"><span class=\"z-keyword z-operator z-custom z-postfix z-unary z-swift\">.<\/span>onTapGesture {\n<\/span><span class=\"z-source z-swift\">    eventBus<span class=\"z-keyword z-operator z-custom z-postfix z-unary z-swift\">.<\/span>send(Command<span class=\"z-keyword z-operator z-custom z-postfix z-unary z-swift\">.<\/span>PlaylistSelected(playlist<span class=\"z-keyword z-operator z-custom z-postfix z-unary z-swift\">.<\/span>id))\n<\/span><span class=\"z-source z-swift\">}\n<\/span><\/code><\/pre>\n<p>Any view has access to the event bus and sends commands to it. Commands are listened by<\/p>\n<ul>\n<li><strong>Coordinator<\/strong> - to change the navigation state<\/li>\n<li><strong>Services<\/strong> - to update the state of the app<\/li>\n<li><strong>ViewModels<\/strong> - to update the state of the view if neccessary<\/li>\n<\/ul>\n<h2 id=\"multi-platform-support\">Multi-platform support<\/h2>\n<p>Different platforms might require different navigation flows. Complications arrise when the navigation is different with some pieces being the same. The first solution that comes to mind is to try to reuse as much as possible. But because there are just a few platforms to support, and new platforms don\u2019t appear other night, I think the best way here is to have separate <strong>Coordinator<\/strong> and <strong>NavigationViewModel<\/strong> for each platform.<\/p>\n<p>As Martin Fowler said, copy it three times and only the fourth time refactor it. If I will have to support more than 4 platforms, then I will think about a more generic solution. Currently in Apple world, I have to support iOS and macOS.<\/p>\n<h2 id=\"conclusion\">Conclusion<\/h2>\n<p>I have been experimenting with SwiftUI for a while now, and I have found that it is a good framework for building navigation systems. SwiftUI is a declarative framework that allows me to define your UI in a simple and concise way. By using an event-driven architecture, I can create a navigation system that is easy to understand and maintain. I am hoping to continue the experimentation and see how far I can push SwiftUI to build more complex navigation systems.<\/p>\n<p>A big advantage of using EDA architecture is that the code becomes truly <strong>asynchronous<\/strong>. Events can be generated anytime and anywhere. Adding a new view to the system becomes simpler because of the decoupling of the views. The views don\u2019t have to know about each other, they only have to know about the events. Because the views are decoupled, it can be combined in different ways to create different navigation flows. The navigation flow is easy to switch to a different one; for example, different platforms can have different navigation flows.<\/p>\n<p>I don\u2019t think the above solution is following the EDA architecture best practices as described by the book. As I haven\u2019t finished it yet, I am still learning and experimenting with the concepts. I am trying to apply the concepts to the iOS app and see how they work in practice. I am hoping to learn more about EDA and apply it to other projects in the future.<\/p>\n"},{"title":"Event driven architecture in iOS","pubDate":"Wed, 16 Oct 2024 00:00:00 +0000","author":"Ion Ostafi","link":"https:\/\/ionostafi.com\/blog\/ios-event-driven-architecture\/","guid":"https:\/\/ionostafi.com\/blog\/ios-event-driven-architecture\/","description":"<h2 id=\"architecture-of-the-m25-project\">Architecture of the M25 project<\/h2>\n<p>This is a continuation of previous article <a href=\"..\/m25-project\/\">M25 project<\/a>. For the M25 project I have chosen to go with Event Driven Architecture. In this article, I\u2019ll focus mainly on the communication patterns and events. Other topics, such as testing, mocking, simulating events, integration testing, and microservices in an iOS app, will be briefly mentioned but not detailed or exemplified.<\/p>\n<h2 id=\"definition\">Definition<\/h2>\n<p><a href=\"https:\/\/aws.amazon.com\/event-driven-architecture\/\">A defintion by Amazon<\/a>. An event-driven architecture (EDA) uses events to trigger and communicate between decoupled services and is common in modern applications built with microservices. An event is a change in state, or an update, like an item being placed in a shopping cart on an e-commerce website. Events can either carry the state (the item purchased, its price, and a delivery address) or events can be identifiers (a notification that an order was shipped).<\/p>\n<h2 id=\"motivation\">Motivation<\/h2>\n<p>For the M25 project, I want to go beyond what I worked with, what I saw in the community, and what is the default code structure for any iOS project. To challenge myself technically, I\u2019ve chosen an event-based architecture. I want to use microservices-inspired patterns on the mobile by modularising the app into decoupled components and use an event bus for communication between them.<\/p>\n<p>The idea was born when I started to think of a new architecture for the Crunchyroll iOS application, where I am working on full-time. At first,  I only considered event-based communication between specific components. Later, when the idea evolved and I talked to multiple engineers in the company, someone mentioned what if we go full event-based. I was skeptical of the idea as event-driven systems can become difficult to manage if not carefully implemented. We haven\u2019t adoped the idea in my team.<\/p>\n<p>Still, I decided to try the idea. I completed a proof-of-concept and converted an iOS app from the traditional way of writing apps to the event-driven architecture. Several key advantages convinced me to choose EDA for the M25:<\/p>\n<p><strong>Decoupling between components<\/strong><\/p>\n<p>Having a clean ViewModel without referencing one or multiple services makes it absolutely decoupled from the services. While using protocols to achieve similar decoupling is possible, it involves more boilerplate code\u2014defining protocols, implementing them, writing mocks, and managing dependency injection (DI). With event-driven architecture, I only need the event, its implementation, and the subscription logic.<\/p>\n<p><strong>Reduced Dependency Injection Code<\/strong><\/p>\n<p>The driving force for me after I finished my first proof-of-concept is that I almost deleted the whole dependency injection code. Every service or ViewModel is created without any other dependencies because there is no need for a reference to communicate - communication is done through decoupled events. A traditional DI requires time or a good framework to make the DI code transparent so that developers don\u2019t waste time wiring objects manually but instead focus on business logic code - this is called convention over configuration. I haven\u2019t tried all the DI frameworks out there, but I used Swinject and it has some support for automatic code wiring based on files. It\u2019s not fully automated.<\/p>\n<p><strong>Simplified Testing<\/strong><\/p>\n<p>Instead of writing unit tests for each individual service function, which would be time-consuming, I\u2019m focusing on integration testing. I simulate the entire system minus external dependencies, sending fake events to test ViewModel state transitions. External dependencies (like Apple frameworks or third-party SDKs) are abstracted behind facades, allowing me to control and mock them during tests.<\/p>\n<p>For testing, the <strong>WHEN<\/strong> is the moment an event is sent (triggered by user or system actions), the <strong>GIVEN<\/strong> is the setup of fake events, and the <strong>THEN<\/strong> involves asserting the resulting ViewModel state.<\/p>\n<p><strong>Faster Development<\/strong><\/p>\n<p>I found that having less dependency injection code, fewer protocols, mocks, and unit tests boosts productivity. Instead of focusing on writing interfaces and figuring out how to segregate them, which is what many developers spend a decent amount of time on in VIPER architecture (as an example), I concentrate on the implementation of services, events, and the View. I\u2019ve noticed that whenever I need to move code around in traditional architectures, I often have to re-write interfaces and re-wire components\u2014things that I don\u2019t need to do with an event-driven architecture (EDA).<\/p>\n<h2 id=\"things-to-be-aware-of\">Things to be aware of<\/h2>\n<p>Event driven communication between components comes with disadvantages, as in any decision in life, there is no\ngood and bad, there is only a trade-off. Each choice should be evaluated based on the specific use case, the people involved, and other factors.<\/p>\n<p>Some <em>trade-offs<\/em> I have to keep in mind:<\/p>\n<p><strong>Mindset shift<\/strong><\/p>\n<p>The call\/response using direct object references is the request\/response pattern. Programming using this pattern is following the traditional imperative paradigm. If I want to change the state of the UI, I call a method that loads data, I wait for the response and then update the UI. If a tap is happening, I call a method to change the system state, I wait for the response and then update the UI. In event driven architecture, I step into a declarative paradigm where I react to changes. If I want to update the UI, I am waiting for the desired event to happen. I don\u2019t know when that event will happen, but if it happens, I will update the UI.<\/p>\n<p><strong>Debugging<\/strong><\/p>\n<p>In the traditional procedural paradigm, If I have a problem and want to debug it I can put a breakpoint, and start following the calls using next step, step-in\/out. While inspecting the state of the program at each step I can find the issue fast. With reactive paradigm, I need to find other ways of debugging. And one that I found to work pretty well is the logging of events. I can still use the debugger, but instead of a single break point, I will have to put breakpoints in places that trigger events I need to debug.<\/p>\n<p><strong>Events order<\/strong><\/p>\n<p>Observers receive events in the order of their subscription, meaning that the timing of when a component subscribes can impact the behavior of the system. I have to design code so that services, view models, and other components do not rely on a specific event order, as this can lead to brittle or confusing dependencies.<\/p>\n<aside class=\"alert\"><p>While these may seem like disadvantages at first, they\u2019re largely a matter of adapting your mindset and using appropriate tools. Any architecture can have debugging complexities, especially when concurrency is involved.<\/p>\n<\/aside><h2 id=\"comparison-with-other-event-bus-implementations\">Comparison with other event bus implementations<\/h2>\n<p>A more traditional event bus implementation is by using a central \u201cbus\u201d, an object that is used to send and listen to events. A perfectly usable solution. Such solutions can be found on github as an open source library. I have read the source code of the three top libraries and all of them are not using the Combine framework, I suppose it was created before Combine was released by apple.<\/p>\n<p>The approach I take is to have a <code>publisher<\/code> (bus) for each event I am sending, this makes the listening very granular. I can listen to just one event or multiple events using <code>CombineLatest<\/code>. I can create my own channels customized to my needs, as the example with <code>EventChannel.all<\/code> to be able to listen to all events. I think that the channel solution can be extended to more needs.<\/p>\n<p>If I choose to always use a single channel for events distribution, like traditional event buses, it means that somewhere in the stream there will be a filter by events. An operation that can be avoided easily, and if there is a route with less code and operations, then I will choose that route.<\/p>\n<h2 id=\"simple-event-bus-design-using-swift-and-combine\">Simple event bus design using Swift and Combine<\/h2>\n<p>I found a simple, loveable, powerful implementation of an event. I tried a few different designs, but here is one I love very much. This one doesn\u2019t use a central event bus pattern; the \u201cbus\u201d is part of the event definition. Each event can be subscribed separately or combined with others using Combine publishers.<\/p>\n<pre data-lang=\"swift\" class=\"language-swift z-code\"><code class=\"language-swift\" data-lang=\"swift\"><span class=\"z-source z-swift\"><span class=\"z-keyword z-other z-access-level-modifier z-swift\">public<\/span> <span class=\"z-storage z-type z-swift\">protocol<\/span> Event {\n<\/span><span class=\"z-source z-swift\">    <span class=\"z-keyword z-other z-declaration-modifier z-swift\">static<\/span> <span class=\"z-storage z-type z-swift\">var<\/span> publisher: PassthroughSubject<span class=\"z-keyword z-operator z-comparative z-swift\">&lt;<\/span><span class=\"z-keyword z-other z-statement z-swift\">Self<\/span>, Never<span class=\"z-keyword z-operator z-comparative z-swift\">&gt;<\/span> { <span class=\"z-keyword z-other z-swift\">get<\/span> }\n<\/span><span class=\"z-source z-swift\">}\n<\/span><\/code><\/pre>\n<p>Events definition examples<\/p>\n<pre data-lang=\"swift\" class=\"language-swift z-code\"><code class=\"language-swift\" data-lang=\"swift\"><span class=\"z-source z-swift\"><span class=\"z-comment z-line z-double-slash z-swift\"><span class=\"z-punctuation z-definition z-comment z-line z-double-slash z-swift\">\/\/<\/span> Example of an event without a message<\/span>\n<\/span><span class=\"z-source z-swift\"><span class=\"z-keyword z-other z-access-level-modifier z-swift\">public<\/span> <span class=\"z-storage z-type z-swift\">struct<\/span> LoadPlanEvent: Event {\n<\/span><span class=\"z-source z-swift\">    <span class=\"z-keyword z-other z-access-level-modifier z-swift\">public<\/span> <span class=\"z-keyword z-other z-declaration-modifier z-swift\">static<\/span> <span class=\"z-storage z-type z-swift\">let<\/span> publisher <span class=\"z-keyword z-operator z-assignment z-swift\">=<\/span> PassthroughSubject<span class=\"z-keyword z-operator z-comparative z-swift\">&lt;<\/span><span class=\"z-keyword z-other z-statement z-swift\">Self<\/span>, Never<span class=\"z-keyword z-operator z-comparative z-swift\">&gt;<\/span>()\n<\/span><span class=\"z-source z-swift\">}\n<\/span><span class=\"z-source z-swift\">\n<\/span><span class=\"z-source z-swift\"><span class=\"z-comment z-line z-double-slash z-swift\"><span class=\"z-punctuation z-definition z-comment z-line z-double-slash z-swift\">\/\/<\/span> Example of an event with a message<\/span>\n<\/span><span class=\"z-source z-swift\"><span class=\"z-keyword z-other z-access-level-modifier z-swift\">public<\/span> <span class=\"z-storage z-type z-swift\">struct<\/span> PlanProgressUpdatedEvent: Event {\n<\/span><span class=\"z-source z-swift\">    <span class=\"z-keyword z-other z-access-level-modifier z-swift\">public<\/span> <span class=\"z-keyword z-other z-declaration-modifier z-swift\">static<\/span> <span class=\"z-storage z-type z-swift\">let<\/span> publisher <span class=\"z-keyword z-operator z-assignment z-swift\">=<\/span> PassthroughSubject<span class=\"z-keyword z-operator z-comparative z-swift\">&lt;<\/span><span class=\"z-keyword z-other z-statement z-swift\">Self<\/span>, Never<span class=\"z-keyword z-operator z-comparative z-swift\">&gt;<\/span>()\n<\/span><span class=\"z-source z-swift\">    <span class=\"z-keyword z-other z-access-level-modifier z-swift\">public<\/span> <span class=\"z-storage z-type z-swift\">var<\/span> planProgress: PlanProgress\n<\/span><span class=\"z-source z-swift\">\n<\/span><span class=\"z-source z-swift\">    <span class=\"z-keyword z-other z-access-level-modifier z-swift\">public<\/span> <span class=\"z-keyword z-declaration z-swift\">init<\/span>(planProgress: PlanProgress) {\n<\/span><span class=\"z-source z-swift\">        <span class=\"z-keyword z-other z-statement z-swift\">self<\/span><span class=\"z-keyword z-operator z-custom z-postfix z-unary z-swift\">.<\/span>planProgress <span class=\"z-keyword z-operator z-assignment z-swift\">=<\/span> planProgress\n<\/span><span class=\"z-source z-swift\">    }\n<\/span><span class=\"z-source z-swift\">}\n<\/span><\/code><\/pre>\n<p>Events can be sent from anywhere using the event definition to access the publisher.<\/p>\n<pre data-lang=\"swift\" class=\"language-swift z-code\"><code class=\"language-swift\" data-lang=\"swift\"><span class=\"z-source z-swift\">LoadPlanEvent<span class=\"z-keyword z-operator z-custom z-postfix z-unary z-swift\">.<\/span>publisher<span class=\"z-keyword z-operator z-custom z-postfix z-unary z-swift\">.<\/span>send(<span class=\"z-keyword z-operator z-custom z-prefix z-unary z-swift\">.<\/span><span class=\"z-keyword z-declaration z-swift\">init<\/span>())\n<\/span><span class=\"z-source z-swift\">PlanProgressUpdatedEvent<span class=\"z-keyword z-operator z-custom z-postfix z-unary z-swift\">.<\/span>publisher<span class=\"z-keyword z-operator z-custom z-postfix z-unary z-swift\">.<\/span>send(<span class=\"z-keyword z-operator z-custom z-prefix z-unary z-swift\">.<\/span><span class=\"z-keyword z-declaration z-swift\">init<\/span>(planProgress: <span class=\"z-keyword z-operator z-custom z-prefix z-unary z-swift\">.<\/span>empty()))\n<\/span><\/code><\/pre>\n<p>Examples of observing events in a SwiftUI ObservableObject<\/p>\n<pre data-lang=\"swift\" class=\"language-swift z-code\"><code class=\"language-swift\" data-lang=\"swift\"><span class=\"z-source z-swift\"><span class=\"z-storage z-type z-swift\">class<\/span> PomodoroTimerViewModel: ObservableObject {\n<\/span><span class=\"z-source z-swift\">    <span class=\"z-storage z-modifier z-attribute z-swift\"><span class=\"z-punctuation z-definition z-attribute z-swift\">@<\/span>MainActor<\/span> <span class=\"z-storage z-modifier z-attribute z-swift\"><span class=\"z-punctuation z-definition z-attribute z-swift\">@<\/span>Published<\/span> <span class=\"z-storage z-type z-swift\">var<\/span> loaded <span class=\"z-keyword z-operator z-assignment z-swift\">=<\/span> <span class=\"z-keyword z-constant z-boolean z-swift\">false<\/span>\n<\/span><span class=\"z-source z-swift\">    <span class=\"z-storage z-modifier z-attribute z-swift\"><span class=\"z-punctuation z-definition z-attribute z-swift\">@<\/span>MainActor<\/span> <span class=\"z-storage z-modifier z-attribute z-swift\"><span class=\"z-punctuation z-definition z-attribute z-swift\">@<\/span>Published<\/span> <span class=\"z-storage z-type z-swift\">var<\/span> planProgress: PlanProgress <span class=\"z-keyword z-operator z-assignment z-swift\">=<\/span> <span class=\"z-keyword z-operator z-custom z-prefix z-unary z-swift\">.<\/span>empty()\n<\/span><span class=\"z-source z-swift\">\n<\/span><span class=\"z-source z-swift\">    <span class=\"z-keyword z-declaration z-swift\">init<\/span>() {\n<\/span><span class=\"z-source z-swift\">        LoadPlanEvent<span class=\"z-keyword z-operator z-custom z-postfix z-unary z-swift\">.<\/span>publisher<span class=\"z-keyword z-operator z-custom z-postfix z-unary z-swift\">.<\/span>map { _ <span class=\"z-keyword z-control z-loop z-swift\">in<\/span> <span class=\"z-keyword z-constant z-boolean z-swift\">false<\/span> }<span class=\"z-keyword z-operator z-custom z-postfix z-unary z-swift\">.<\/span>assign(to: <span class=\"z-keyword z-operator z-bitwise z-swift\">&amp;<\/span>$loaded)\n<\/span><span class=\"z-source z-swift\">        PlanProgressUpdatedEvent<span class=\"z-keyword z-operator z-custom z-postfix z-unary z-swift\">.<\/span>publisher<span class=\"z-keyword z-operator z-custom z-postfix z-unary z-swift\">.<\/span>map(\\<span class=\"z-keyword z-operator z-custom z-postfix z-unary z-swift\">.<\/span>planProgress)<span class=\"z-keyword z-operator z-custom z-postfix z-unary z-swift\">.<\/span>assign(to: <span class=\"z-keyword z-operator z-bitwise z-swift\">&amp;<\/span>$planProgress)\n<\/span><span class=\"z-source z-swift\">    }\n<\/span><span class=\"z-source z-swift\">}\n<\/span><\/code><\/pre>\n<p>The ViewModel could be renamed to a Store. I am using the ViewModel name because I will use the MVVM architectural pattern and the store will be transformed to a ViewModel. ViewModel doesn\u2019t have reference to any service; it reacts to changes in the system by listening to the events it is interested in. In this case, it\u2019s <code>LoadPlanEvent<\/code> and <code>PlanProgressUpdatedEvent<\/code>. Those events could be sent by any part of the system; in my case, it would be one or multiple services to send those events.<\/p>\n<h2 id=\"improved-event-bus-design\">Improved event bus design<\/h2>\n<p>With time, I noticed two things I needed from the events:<\/p>\n<ul>\n<li>A way to hook into the stream and log the events (observability)<\/li>\n<li>Slight repetition in code <code>.publisher.send(<\/code>) is used on each event send.<\/li>\n<li>Some messages have to be stored so I can directly check the last value that was sent for an event.<\/li>\n<\/ul>\n<p>To solve the above, I made the following update to the protocol and added a default implementation.<\/p>\n<pre data-lang=\"swift\" class=\"language-swift z-code\"><code class=\"language-swift\" data-lang=\"swift\"><span class=\"z-source z-swift\"><span class=\"z-keyword z-other z-access-level-modifier z-swift\">public<\/span> <span class=\"z-storage z-type z-swift\">protocol<\/span> Event {\n<\/span><span class=\"z-source z-swift\">    associatedtype S: Subject<span class=\"z-keyword z-operator z-comparative z-swift\">&lt;<\/span><span class=\"z-keyword z-other z-statement z-swift\">Self<\/span>, Never<span class=\"z-keyword z-operator z-comparative z-swift\">&gt;<\/span>\n<\/span><span class=\"z-source z-swift\">    <span class=\"z-keyword z-other z-declaration-modifier z-swift\">static<\/span> <span class=\"z-storage z-type z-swift\">var<\/span> subject: S { <span class=\"z-keyword z-other z-swift\">get<\/span> }\n<\/span><span class=\"z-source z-swift\">    <span class=\"z-keyword z-other z-declaration-modifier z-swift\">static<\/span> <span class=\"z-meta z-function-declaration z-swift\"><span class=\"z-storage z-type z-function z-swift\">func<\/span> <span class=\"z-entity z-type z-function z-swift\">send<\/span><span class=\"z-meta z-parameter-clause z-swift\"><span class=\"z-punctuation z-definition z-function-arguments z-begin z-swift\">(<\/span>_: <span class=\"z-keyword z-other z-statement z-swift\">Self<\/span><span class=\"z-punctuation z-definition z-function-arguments z-end z-swift\">)<\/span><\/span>\n<\/span><\/span><span class=\"z-source z-swift\"><span class=\"z-meta z-function-declaration z-swift\">}<\/span>\n<\/span><\/code><\/pre>\n<p>Now, the events can store either an <code>PassthroughSubject<\/code> or a <code>CurrentValueSubject<\/code>.\nThe senders of the events can directly call send without having to access the <code>subject<\/code>, the usage becomes:<\/p>\n<pre data-lang=\"swift\" class=\"language-swift z-code\"><code class=\"language-swift\" data-lang=\"swift\"><span class=\"z-source z-swift\"><span class=\"z-comment z-line z-double-slash z-swift\"><span class=\"z-punctuation z-definition z-comment z-line z-double-slash z-swift\">\/\/<\/span> current<\/span>\n<\/span><span class=\"z-source z-swift\">LoadPlanEvent<span class=\"z-keyword z-operator z-custom z-postfix z-unary z-swift\">.<\/span>send(<span class=\"z-keyword z-operator z-custom z-prefix z-unary z-swift\">.<\/span><span class=\"z-keyword z-declaration z-swift\">init<\/span>())\n<\/span><span class=\"z-source z-swift\">PlanProgressUpdatedEvent<span class=\"z-keyword z-operator z-custom z-postfix z-unary z-swift\">.<\/span>send(<span class=\"z-keyword z-operator z-custom z-prefix z-unary z-swift\">.<\/span><span class=\"z-keyword z-declaration z-swift\">init<\/span>(planProgress: <span class=\"z-keyword z-operator z-custom z-prefix z-unary z-swift\">.<\/span>empty()))\n<\/span><span class=\"z-source z-swift\">\n<\/span><span class=\"z-source z-swift\"><span class=\"z-comment z-line z-double-slash z-swift\"><span class=\"z-punctuation z-definition z-comment z-line z-double-slash z-swift\">\/\/<\/span> previous<\/span>\n<\/span><span class=\"z-source z-swift\">LoadPlanEvent<span class=\"z-keyword z-operator z-custom z-postfix z-unary z-swift\">.<\/span>publisher<span class=\"z-keyword z-operator z-custom z-postfix z-unary z-swift\">.<\/span>send(<span class=\"z-keyword z-operator z-custom z-prefix z-unary z-swift\">.<\/span><span class=\"z-keyword z-declaration z-swift\">init<\/span>())\n<\/span><span class=\"z-source z-swift\">PlanProgressUpdatedEvent<span class=\"z-keyword z-operator z-custom z-postfix z-unary z-swift\">.<\/span>publisher<span class=\"z-keyword z-operator z-custom z-postfix z-unary z-swift\">.<\/span>send(<span class=\"z-keyword z-operator z-custom z-prefix z-unary z-swift\">.<\/span><span class=\"z-keyword z-declaration z-swift\">init<\/span>(planProgress: <span class=\"z-keyword z-operator z-custom z-prefix z-unary z-swift\">.<\/span>empty()))\n<\/span><\/code><\/pre>\n<p>I didn\u2019t implement the <code>send<\/code> method in each event, the event implementation remains almost unchanged, just replaced the <code>publisher<\/code> with <code>subject<\/code>. Instead, I created an extension for the publisher with default implementation to create a way to hook into the events.<\/p>\n<pre data-lang=\"swift\" class=\"language-swift z-code\"><code class=\"language-swift\" data-lang=\"swift\"><span class=\"z-source z-swift\"><span class=\"z-keyword z-other z-access-level-modifier z-swift\">public<\/span> <span class=\"z-storage z-type z-swift\">class<\/span> EventChannel {\n<\/span><span class=\"z-source z-swift\">    <span class=\"z-keyword z-other z-access-level-modifier z-swift\">public<\/span> <span class=\"z-keyword z-other z-declaration-modifier z-swift\">static<\/span> <span class=\"z-storage z-type z-swift\">let<\/span> all <span class=\"z-keyword z-operator z-assignment z-swift\">=<\/span> PassthroughSubject<span class=\"z-keyword z-operator z-comparative z-swift\">&lt;<\/span>any Event, Never<span class=\"z-keyword z-operator z-comparative z-swift\">&gt;<\/span>()\n<\/span><span class=\"z-source z-swift\">}\n<\/span><span class=\"z-source z-swift\">\n<\/span><span class=\"z-source z-swift\"><span class=\"z-keyword z-other z-access-level-modifier z-swift\">public<\/span> <span class=\"z-storage z-type z-swift\">extension<\/span> Event {\n<\/span><span class=\"z-source z-swift\">    <span class=\"z-keyword z-other z-declaration-modifier z-swift\">static<\/span> <span class=\"z-meta z-function-declaration z-swift\"><span class=\"z-storage z-type z-function z-swift\">func<\/span> <span class=\"z-entity z-type z-function z-swift\">send<\/span><span class=\"z-meta z-parameter-clause z-swift\"><span class=\"z-punctuation z-definition z-function-arguments z-begin z-swift\">(<\/span>_ value: <span class=\"z-keyword z-other z-statement z-swift\">Self<\/span><span class=\"z-punctuation z-definition z-function-arguments z-end z-swift\">)<\/span><\/span> <span class=\"z-punctuation z-definition z-code-block z-begin z-swift\">{<\/span>\n<\/span><\/span><span class=\"z-source z-swift\"><span class=\"z-meta z-function-declaration z-swift\">        EventChannel<span class=\"z-keyword z-operator z-custom z-postfix z-unary z-swift\">.<\/span>all<span class=\"z-keyword z-operator z-custom z-postfix z-unary z-swift\">.<\/span>send(value)\n<\/span><\/span><span class=\"z-source z-swift\"><span class=\"z-meta z-function-declaration z-swift\">        subject<span class=\"z-keyword z-operator z-custom z-postfix z-unary z-swift\">.<\/span>send(value)\n<\/span><\/span><span class=\"z-source z-swift\"><span class=\"z-meta z-function-declaration z-swift\">    <span class=\"z-punctuation z-definition z-code-block z-end z-swift\">}<\/span><\/span>\n<\/span><span class=\"z-source z-swift\">\n<\/span><span class=\"z-source z-swift\">    <span class=\"z-keyword z-other z-declaration-modifier z-swift\">static<\/span> <span class=\"z-storage z-type z-swift\">var<\/span> publisher: AnyPublisher<span class=\"z-keyword z-operator z-comparative z-swift\">&lt;<\/span><span class=\"z-keyword z-other z-statement z-swift\">Self<\/span>, Never<span class=\"z-keyword z-operator z-comparative z-swift\">&gt;<\/span> {\n<\/span><span class=\"z-source z-swift\">        subject<span class=\"z-keyword z-operator z-custom z-postfix z-unary z-swift\">.<\/span>eraseToAnyPublisher()\n<\/span><span class=\"z-source z-swift\">    }\n<\/span><span class=\"z-source z-swift\">}\n<\/span><\/code><\/pre>\n<p><code>EventChannel.all<\/code> is used to hook into all event streams. I am logging the events on the console\nfor now. But I can create a service to listen and record all the event, so later I can simulate all those events helping\nme in testing.<\/p>\n<h2 id=\"example-using-spotify-to-display-playlist\">Example using spotify to display playlist<\/h2>\n<p>The example is simplified to display the charactersistics of the EDA architecture and not technically how to fetch and use the spotify API. The spotify API is available through the use of <a href=\"https:\/\/developer.spotify.com\/documentation\/web-api\">web API<\/a> or <a href=\"https:\/\/github.com\/spotify\/ios-sdk\">iOS SDK<\/a>. The implementation of UI is simplified as well.<\/p>\n<p><strong>The View<\/strong><\/p>\n<pre data-lang=\"swift\" class=\"language-swift z-code\"><code class=\"language-swift\" data-lang=\"swift\"><span class=\"z-source z-swift\"><span class=\"z-storage z-type z-swift\">struct<\/span> ChoosePlaylistView: View {\n<\/span><span class=\"z-source z-swift\">    <span class=\"z-storage z-modifier z-attribute z-swift\"><span class=\"z-punctuation z-definition z-attribute z-swift\">@<\/span>EnvironmentObject<\/span> <span class=\"z-storage z-type z-swift\">var<\/span> viewModel: ChoosePlaylistViewModel\n<\/span><span class=\"z-source z-swift\">\n<\/span><span class=\"z-source z-swift\">    <span class=\"z-storage z-type z-swift\">var<\/span> body: some View {\n<\/span><span class=\"z-source z-swift\">        List(viewModel<span class=\"z-keyword z-operator z-custom z-postfix z-unary z-swift\">.<\/span>playlists) { playlist <span class=\"z-keyword z-control z-loop z-swift\">in<\/span>\n<\/span><span class=\"z-source z-swift\">            PlaylistView(playlist: playlist)\n<\/span><span class=\"z-source z-swift\">        }\n<\/span><span class=\"z-source z-swift\">        <span class=\"z-keyword z-operator z-custom z-prefix z-unary z-swift\">.<\/span>overlay {\n<\/span><span class=\"z-source z-swift\">            <span class=\"z-keyword z-control z-if z-swift\">if<\/span> viewModel<span class=\"z-keyword z-operator z-custom z-postfix z-unary z-swift\">.<\/span>isLoading {\n<\/span><span class=\"z-source z-swift\">                ProgressView()<span class=\"z-keyword z-operator z-custom z-postfix z-unary z-swift\">.<\/span>progressViewStyle(<span class=\"z-keyword z-operator z-custom z-prefix z-unary z-swift\">.<\/span>circular)\n<\/span><span class=\"z-source z-swift\">            }\n<\/span><span class=\"z-source z-swift\">        }\n<\/span><span class=\"z-source z-swift\">        <span class=\"z-keyword z-operator z-custom z-prefix z-unary z-swift\">.<\/span>onAppear {\n<\/span><span class=\"z-source z-swift\">            UpdatePlaylistsRequestedEvent<span class=\"z-keyword z-operator z-custom z-postfix z-unary z-swift\">.<\/span>send(<span class=\"z-keyword z-operator z-custom z-prefix z-unary z-swift\">.<\/span><span class=\"z-keyword z-declaration z-swift\">init<\/span>())\n<\/span><span class=\"z-source z-swift\">        }\n<\/span><span class=\"z-source z-swift\">    }\n<\/span><span class=\"z-source z-swift\">}\n<\/span><\/code><\/pre>\n<p>Each time this view appears, I am sending an event to notify the system that there is a need for refreshed playlists.<\/p>\n<p>The View and ViewModel is one place where I am using object reference. View is referencing the ViewModel. ViewModel is created outside of the view, and added as an EnvironmentObject. All the ViewModels in the app are created at app launch and added to SwiftUI environment.<\/p>\n<pre data-lang=\"swift\" class=\"language-swift z-code\"><code class=\"language-swift\" data-lang=\"swift\"><span class=\"z-source z-swift\"><span class=\"z-comment z-line z-double-slash z-swift\"><span class=\"z-punctuation z-definition z-comment z-line z-double-slash z-swift\">\/\/<\/span> Injectig all the view models in the Environment at app launch<\/span>\n<\/span><span class=\"z-source z-swift\">MainCoordinator()\n<\/span><span class=\"z-source z-swift\">    <span class=\"z-keyword z-operator z-custom z-prefix z-unary z-swift\">.<\/span>environmentObject(compositor<span class=\"z-keyword z-operator z-custom z-postfix z-unary z-swift\">.<\/span>navViewModel)\n<\/span><span class=\"z-source z-swift\">    <span class=\"z-keyword z-operator z-custom z-prefix z-unary z-swift\">.<\/span>environmentObject(compositor<span class=\"z-keyword z-operator z-custom z-postfix z-unary z-swift\">.<\/span>errorViewModel)\n<\/span><span class=\"z-source z-swift\">    <span class=\"z-keyword z-operator z-custom z-prefix z-unary z-swift\">.<\/span>environmentObject(compositor<span class=\"z-keyword z-operator z-custom z-postfix z-unary z-swift\">.<\/span>choosePlaylistViewModel)\n<\/span><span class=\"z-source z-swift\">    <span class=\"z-keyword z-operator z-custom z-prefix z-unary z-swift\">.<\/span>environmentObject(compositor<span class=\"z-keyword z-operator z-custom z-postfix z-unary z-swift\">.<\/span>generatedPlaylisViewModel)\n<\/span><span class=\"z-source z-swift\">    <span class=\"z-keyword z-operator z-custom z-prefix z-unary z-swift\">.<\/span>environmentObject(compositor<span class=\"z-keyword z-operator z-custom z-postfix z-unary z-swift\">.<\/span>deviceActivationViewModel)\n<\/span><\/code><\/pre>\n<aside class=\"alert\"><p>To instantiate all ViewModels at the app launch isn\u2019t what I want, but for now I haven\u2019t found another way to graciously handle the creation of ViewModels<\/p>\n<\/aside>\n<p><strong>The domain model<\/strong><\/p>\n<pre data-lang=\"swift\" class=\"language-swift z-code\"><code class=\"language-swift\" data-lang=\"swift\"><span class=\"z-source z-swift\"><span class=\"z-keyword z-other z-access-level-modifier z-swift\">public<\/span> <span class=\"z-storage z-type z-swift\">struct<\/span> Playlist: BaseObject {\n<\/span><span class=\"z-source z-swift\">    <span class=\"z-keyword z-other z-access-level-modifier z-swift\">public<\/span> <span class=\"z-storage z-type z-swift\">let<\/span> id: <span class=\"z-support z-type z-swift\">String<\/span>\n<\/span><span class=\"z-source z-swift\">    <span class=\"z-keyword z-other z-access-level-modifier z-swift\">public<\/span> <span class=\"z-storage z-type z-swift\">let<\/span> songsCount: <span class=\"z-support z-type z-swift\">Int<\/span>\n<\/span><span class=\"z-source z-swift\">    <span class=\"z-keyword z-other z-access-level-modifier z-swift\">public<\/span> <span class=\"z-storage z-type z-swift\">let<\/span> name: <span class=\"z-support z-type z-swift\">String<\/span>\n<\/span><span class=\"z-source z-swift\">    <span class=\"z-keyword z-other z-access-level-modifier z-swift\">public<\/span> <span class=\"z-storage z-type z-swift\">let<\/span> image: URL?\n<\/span><span class=\"z-source z-swift\">}\n<\/span><\/code><\/pre>\n<p><strong>The ViewModel<\/strong><\/p>\n<pre data-lang=\"swift\" class=\"language-swift z-code\"><code class=\"language-swift\" data-lang=\"swift\"><span class=\"z-source z-swift\"><span class=\"z-storage z-type z-swift\">class<\/span> ChoosePlaylistViewModel: ObservableObject {\n<\/span><span class=\"z-source z-swift\">    <span class=\"z-storage z-modifier z-attribute z-swift\"><span class=\"z-punctuation z-definition z-attribute z-swift\">@<\/span>MainActor<\/span> <span class=\"z-storage z-modifier z-attribute z-swift\"><span class=\"z-punctuation z-definition z-attribute z-swift\">@<\/span>Published<\/span> <span class=\"z-storage z-type z-swift\">var<\/span> playlists: [Playlist] <span class=\"z-keyword z-operator z-assignment z-swift\">=<\/span> []\n<\/span><span class=\"z-source z-swift\">    <span class=\"z-storage z-modifier z-attribute z-swift\"><span class=\"z-punctuation z-definition z-attribute z-swift\">@<\/span>MainActor<\/span> <span class=\"z-storage z-modifier z-attribute z-swift\"><span class=\"z-punctuation z-definition z-attribute z-swift\">@<\/span>Published<\/span> <span class=\"z-storage z-type z-swift\">var<\/span> isLoading <span class=\"z-keyword z-operator z-assignment z-swift\">=<\/span> <span class=\"z-keyword z-constant z-boolean z-swift\">true<\/span>\n<\/span><span class=\"z-source z-swift\">\n<\/span><span class=\"z-source z-swift\">    <span class=\"z-keyword z-declaration z-swift\">init<\/span>() {\n<\/span><span class=\"z-source z-swift\">        PlaylistsUpdated<span class=\"z-keyword z-operator z-custom z-postfix z-unary z-swift\">.<\/span>publisher\n<\/span><span class=\"z-source z-swift\">            <span class=\"z-keyword z-operator z-custom z-prefix z-unary z-swift\">.<\/span>receive(on: DispatchQueue<span class=\"z-keyword z-operator z-custom z-postfix z-unary z-swift\">.<\/span>main)\n<\/span><span class=\"z-source z-swift\">            <span class=\"z-keyword z-operator z-custom z-prefix z-unary z-swift\">.<\/span>map(\\<span class=\"z-keyword z-operator z-custom z-postfix z-unary z-swift\">.<\/span>playlists)\n<\/span><span class=\"z-source z-swift\">            <span class=\"z-keyword z-operator z-custom z-prefix z-unary z-swift\">.<\/span>assign(to: <span class=\"z-keyword z-operator z-bitwise z-swift\">&amp;<\/span>$playlists)\n<\/span><span class=\"z-source z-swift\">\n<\/span><span class=\"z-source z-swift\">        PlaylistsUpdated<span class=\"z-keyword z-operator z-custom z-postfix z-unary z-swift\">.<\/span>publisher\n<\/span><span class=\"z-source z-swift\">            <span class=\"z-keyword z-operator z-custom z-prefix z-unary z-swift\">.<\/span>receive(on: DispatchQueue<span class=\"z-keyword z-operator z-custom z-postfix z-unary z-swift\">.<\/span>main)\n<\/span><span class=\"z-source z-swift\">            <span class=\"z-keyword z-operator z-custom z-prefix z-unary z-swift\">.<\/span>map { _ <span class=\"z-keyword z-control z-loop z-swift\">in<\/span> <span class=\"z-keyword z-constant z-boolean z-swift\">false<\/span> }\n<\/span><span class=\"z-source z-swift\">            <span class=\"z-keyword z-operator z-custom z-prefix z-unary z-swift\">.<\/span>assign(to: <span class=\"z-keyword z-operator z-bitwise z-swift\">&amp;<\/span>$isLoading)\n<\/span><span class=\"z-source z-swift\">\n<\/span><span class=\"z-source z-swift\">        UpdatePlaylistsRequestedEvent<span class=\"z-keyword z-operator z-custom z-postfix z-unary z-swift\">.<\/span>publisher\n<\/span><span class=\"z-source z-swift\">            <span class=\"z-keyword z-operator z-custom z-prefix z-unary z-swift\">.<\/span>receive(on: DispatchQueue<span class=\"z-keyword z-operator z-custom z-postfix z-unary z-swift\">.<\/span>main)\n<\/span><span class=\"z-source z-swift\">            <span class=\"z-keyword z-operator z-custom z-prefix z-unary z-swift\">.<\/span>map { _ <span class=\"z-keyword z-control z-loop z-swift\">in<\/span> <span class=\"z-keyword z-constant z-boolean z-swift\">true<\/span> }\n<\/span><span class=\"z-source z-swift\">            <span class=\"z-keyword z-operator z-custom z-prefix z-unary z-swift\">.<\/span>assign(to: <span class=\"z-keyword z-operator z-bitwise z-swift\">&amp;<\/span>$isLoading)\n<\/span><span class=\"z-source z-swift\">    }\n<\/span><span class=\"z-source z-swift\">}\n<\/span><\/code><\/pre>\n<p><strong>The service<\/strong><\/p>\n<pre data-lang=\"swift\" class=\"language-swift z-code\"><code class=\"language-swift\" data-lang=\"swift\"><span class=\"z-source z-swift\"><span class=\"z-keyword z-other z-access-level-modifier z-swift\">public<\/span> <span class=\"z-storage z-type z-swift\">class<\/span> SpotifyService {\n<\/span><span class=\"z-source z-swift\">    <span class=\"z-keyword z-other z-access-level-modifier z-swift\">public<\/span> <span class=\"z-keyword z-declaration z-swift\">init<\/span>() {\n<\/span><span class=\"z-source z-swift\">        <span class=\"z-comment z-line z-double-slash z-swift\"><span class=\"z-punctuation z-definition z-comment z-line z-double-slash z-swift\">\/\/<\/span>\/ ... Subscription to other events<\/span>\n<\/span><span class=\"z-source z-swift\">        UpdatePlaylistsRequestedEvent<span class=\"z-keyword z-operator z-custom z-postfix z-unary z-swift\">.<\/span>publisher<span class=\"z-keyword z-operator z-custom z-postfix z-unary z-swift\">.<\/span>sink { [<span class=\"z-keyword z-other z-declaration-modifier z-swift\">weak<\/span> <span class=\"z-keyword z-other z-statement z-swift\">self<\/span>] _ <span class=\"z-keyword z-control z-loop z-swift\">in<\/span>\n<\/span><span class=\"z-source z-swift\">            <span class=\"z-keyword z-other z-statement z-swift\">self<\/span>?<span class=\"z-keyword z-operator z-custom z-postfix z-unary z-swift\">.<\/span>updatePlaylists()\n<\/span><span class=\"z-source z-swift\">        }<span class=\"z-keyword z-operator z-custom z-postfix z-unary z-swift\">.<\/span>store(<span class=\"z-keyword z-control z-loop z-swift\">in<\/span>: <span class=\"z-keyword z-operator z-bitwise z-swift\">&amp;<\/span>bin)\n<\/span><span class=\"z-source z-swift\">    }\n<\/span><span class=\"z-source z-swift\">\n<\/span><span class=\"z-source z-swift\">    <span class=\"z-keyword z-other z-access-level-modifier z-swift\">private<\/span> <span class=\"z-meta z-function-declaration z-swift\"><span class=\"z-storage z-type z-function z-swift\">func<\/span> <span class=\"z-entity z-type z-function z-swift\">updatePlaylists<\/span><span class=\"z-meta z-parameter-clause z-swift\"><span class=\"z-punctuation z-definition z-function-arguments z-begin z-swift\">(<\/span><span class=\"z-punctuation z-definition z-function-arguments z-end z-swift\">)<\/span><\/span> <span class=\"z-punctuation z-definition z-code-block z-begin z-swift\">{<\/span>\n<\/span><\/span><span class=\"z-source z-swift\"><span class=\"z-meta z-function-declaration z-swift\">        Task { [<span class=\"z-keyword z-other z-declaration-modifier z-swift\">weak<\/span> <span class=\"z-keyword z-other z-statement z-swift\">self<\/span>] <span class=\"z-keyword z-control z-loop z-swift\">in<\/span>\n<\/span><\/span><span class=\"z-source z-swift\"><span class=\"z-meta z-function-declaration z-swift\">            <span class=\"z-keyword z-statement z-swift\">guard<\/span> <span class=\"z-storage z-type z-swift\">let<\/span> <span class=\"z-keyword z-other z-statement z-swift\">self<\/span> <span class=\"z-keyword z-operator z-assignment z-swift\">=<\/span> <span class=\"z-keyword z-other z-statement z-swift\">self<\/span> <span class=\"z-keyword z-control z-if z-swift\">else<\/span> { <span class=\"z-keyword z-control z-transfer z-swift\">return<\/span> <span class=\"z-punctuation z-definition z-code-block z-end z-swift\">}<\/span><\/span>\n<\/span><span class=\"z-source z-swift\">            <span class=\"z-storage z-type z-swift\">let<\/span> playlists <span class=\"z-keyword z-operator z-assignment z-swift\">=<\/span> await getUsersPlaylists()\n<\/span><span class=\"z-source z-swift\">            PlaylistsUpdated<span class=\"z-keyword z-operator z-custom z-postfix z-unary z-swift\">.<\/span>send(<span class=\"z-keyword z-operator z-custom z-prefix z-unary z-swift\">.<\/span><span class=\"z-keyword z-declaration z-swift\">init<\/span>(playlists: playlists))\n<\/span><span class=\"z-source z-swift\">        }\n<\/span><span class=\"z-source z-swift\">    }\n<\/span><span class=\"z-source z-swift\">\n<\/span><span class=\"z-source z-swift\">    <span class=\"z-keyword z-other z-access-level-modifier z-swift\">private<\/span> <span class=\"z-meta z-function-declaration z-swift\"><span class=\"z-storage z-type z-function z-swift\">func<\/span> <span class=\"z-entity z-type z-function z-swift\">getUsersPlaylists<\/span><span class=\"z-meta z-parameter-clause z-swift\"><span class=\"z-punctuation z-definition z-function-arguments z-begin z-swift\">(<\/span><span class=\"z-punctuation z-definition z-function-arguments z-end z-swift\">)<\/span><\/span> async <span class=\"z-meta z-function-result z-swift\"><span class=\"z-keyword z-operator z-function-result z-swift\">-&gt;<\/span> [Playlist] <\/span><span class=\"z-punctuation z-definition z-code-block z-begin z-swift\">{<\/span>\n<\/span><\/span><span class=\"z-source z-swift\"><span class=\"z-meta z-function-declaration z-swift\">        <span class=\"z-kewyord z-control z-catch z-swift\">do<\/span> {\n<\/span><\/span><span class=\"z-source z-swift\"><span class=\"z-meta z-function-declaration z-swift\">            <span class=\"z-comment z-line z-double-slash z-swift\"><span class=\"z-punctuation z-definition z-comment z-line z-double-slash z-swift\">\/\/<\/span> request the user&#39;s playlist from web api<\/span>\n<\/span><\/span><span class=\"z-source z-swift\"><span class=\"z-meta z-function-declaration z-swift\">            <span class=\"z-keyword z-control z-transfer z-swift\">return<\/span> playlist\n<\/span><\/span><span class=\"z-source z-swift\"><span class=\"z-meta z-function-declaration z-swift\">        <span class=\"z-punctuation z-definition z-code-block z-end z-swift\">}<\/span><\/span> <span class=\"z-kewyord z-control z-catch z-swift\">catch<\/span> {\n<\/span><span class=\"z-source z-swift\">            ErrorEvent<span class=\"z-keyword z-operator z-custom z-postfix z-unary z-swift\">.<\/span>send(error)\n<\/span><span class=\"z-source z-swift\">            <span class=\"z-keyword z-control z-transfer z-swift\">return<\/span> []\n<\/span><span class=\"z-source z-swift\">        }\n<\/span><span class=\"z-source z-swift\">    }\n<\/span><span class=\"z-source z-swift\">}\n<\/span><\/code><\/pre>\n<p><strong>Diagram<\/strong><\/p>\n<p><img src=\"https:\/\/ionostafi.com\/blog\/ios-event-driven-architecture\/.\/rel_diagram.png\" alt=\"class diagram\" \/><\/p>\n<p>Service is fully decoupled from the View-ViewModel structure. Service is sending Model objects through the use of events.<\/p>\n<h2 id=\"follow-up\">Follow up<\/h2>\n<p>If someone of you want to go and read more about event driven architecture, check this out, it\u2019s a nice source: <a href=\"https:\/\/solace.com\/event-driven-architecture-patterns\/\">The Ultimate Guide to Event-Driven Architecture Patterns<\/a><\/p>\n<p>I the meantime, I am planning to read the book <a href=\"https:\/\/www.goodreads.com\/book\/show\/59637521-practical-event-driven-microservices-architecture\">Practical Event-Driven Microservices Architecture<\/a> by Hugo Filipe Oliveira Rocha.<\/p>\n<p>Continue reading about iOS app navigation using EDA architecture <a href=\"..\/ios-event-driven-navigation\">here<\/a><\/p>\n"},{"title":"Raw thoughts - not for kids","pubDate":"Sat, 05 Oct 2024 00:00:00 +0000","author":"Ion Ostafi","link":"https:\/\/ionostafi.com\/blog\/think\/","guid":"https:\/\/ionostafi.com\/blog\/think\/","description":"<p>Think while eating, think while walking to the office, think while drinking that heavy black mud of cappuccino made by the machine on the desk in the kitchenette, think while watching at the monitor displaying my favorite IDE or code editor with a blinking cursor. The idea materialized in my mind and I see it as clear as a picture sitting in front of me, I start drawing that UML diagram using PlantUML. A few minutes later, I have a simple drawing that is almost identical to the one from my head, but this isn\u2019t going to work, no, it needs some more thinking. Going back to thinking.<\/p>\n<p>Software Engineering is thinking, is reading, is planning how to build that solution that needs to work, to not crash,\nto be modifiable and understandable by other humans. It needs to be readable because reading code takes more time than writing it,\nso I plan for an easy readable code. A readable code is divine, but how to determine that a piece of code is readable is a very tough task because every brain thinks differently and sees things differently, everyone filters the information through a very\ncomplicated filtering mechanism which is created by all the events in life from the moments they are born.\nI need to read books, to read open-source code, to read other people\u2019s code solutions on programming challanges.\nBy reading more I can find a pattern of what is more readable and what is less.<\/p>\n<p>I am noticing it\u2019s badly written, it\u2019s complicated to understand, the structure of the code makes me feel silly.\nAm I silly or the code is bad? Is there an architecture? Of coure there is, every project has an architecture, formal or informal, everyone knows about it or no one knows, but it exists, it\u2019s there, in the code and tools that are used to make the\nproject a real thing.\nI need to make an effort and understand it first before adding new ideas and patterns.\nA big project has reasons for having existing bad code, understanding reasons is crucial because it helps at growing the project in the right way.\nThere are tools for digging reasons, I have to use it, <code>git log -S<\/code>, pickaxe it\u2019s named, because I dig with it, discover, understand.\nCode archeology \u23af so to say \u23af is a very useful technical skill to own.<\/p>\n<p>I\u2019m learning the tools I use daily, I need to use them with ease, and the first thing that gets in the way is\ntouchpad and mouse, it\u2019s the inability to use keyboard to complete a task.\nKeyboard shortcuts is a must learn for every daily tool: Xcode, VSCode, Thunderbird, Firefox, Simulator, MacOS, Terminal, anything.\nKnowing shortcuts saves me from using the touchpad which is imprecise, easy to miss the small icons and buttons.\nI can use the keyboard without looking at the monitor, I can type fast, I can automate my brain to use the shortcuts, this is much\nmore productive than using the mouse.<\/p>\n<p>Back to my thinking, how to make things better, simpler and how to apply the best practices learned other years of practice,\napply what authors like Steve McConnel, Martin Fowler, Rober C. Martin is teaching us in their books.\nNot that million of articles that are 5 minute long read, written poorely and covering just the introduction of a topic.\nIt takes time to get from the initial design to a great design, it takes effort to integrate the new design into the existing one.\nMaking something functional is an achievement, but then, why am I stopping at that first achievement?\nWhy don\u2019t I go further and optimize the functionality, make it better, smaller, easier to understand, why stop at the first?\nBecause first achievement is stronger, it creates stronger emotions making me have a complete day.\nAnd it\u2019s a waste of effort to go and improve an already functional thing, what if improvements will break functionality?\nYeah, the fear of breaking things is strong enoght to block me from thinking.<\/p>\n<p>I will ask why, then again ask why. Never stop asking. I can even question the most fundamental things that I do for years that I think this is the only way.\nBut things do change. As time passes, new ideas emerges, new technology are developed, existing ones gets outdated.\n\u201cChange is the only constant\u201d. Changing requires thinking, deciding on a path forward, choosing one\nway out of many. The life is made up of choosing between trade-offs, and there will never be a good or bad\nchoice, however there is a better choice for the actual situation, for the existing context, my existing knowledge, my friends and coleagues\nand many others; so I have to think about the choice I am making.<\/p>\n<p>The brain needs to think to remain healthy, I have to give it exercises or challanges.\nI should not stick to a single practice, a single rule, a place or an object.\nI have to get out of comfort zone and think how to transform myself to fit in the new environment.\nTry new things, push myself to the limits, find my limits.<\/p>\n<p>Software engineering is thinking.<\/p>\n"},{"title":"The M25 project","pubDate":"Mon, 30 Sep 2024 00:00:00 +0000","author":"Ion Ostafi","link":"https:\/\/ionostafi.com\/blog\/m25-project\/","guid":"https:\/\/ionostafi.com\/blog\/m25-project\/","description":"<p>I once read about how muscles tend to atrophy if they do nothing for a prolonged time, and that it\u2019s better to remind\nthem that they need to keep in shape. Do physical activity every 30 minutes. The idea is that more than 30 minutes of\ndoing nothing is enough for muscles to think they are not needed. Well, I am sure there are better medical explanations\nfor this phenomenon. My job and probably yours too, requires sitting in front of a computer for many hours a day.\nIf that\u2019s true, you need to focus and take breaks.<\/p>\n<p>There is a time management technique named pomodoro - 25 minutes of work and five of break. I tried it several times.\nAt the beginning it didn\u2019t work, so I dropped the idea.\nIt doesn\u2019t feel right to stop my focused work when I hear the timer. Most of the time, I am in a deep focus state.<\/p>\n<p>Another day, I hear the timer, I know that I need to take a break, but I am in the flow state.\nI contine my work with the music in my ears. After a few minutes, I forget I have to stop.\nIt\u2019s only when the physical pain reminds me to move my back.<\/p>\n<blockquote>\n<p>\u201cFlow is the melting together of action and consciousness; the state of finding a balance between a skill and how challenging that task is. It requires a high level of concentration.\u201d (<a href=\"https:\/\/en.wikipedia.org\/wiki\/Flow_(psychology)\">wikipedia<\/a>).<\/p>\n<\/blockquote>\n<p>A few years later, I tried a different approach\u2014using a new \u201cmarker\u201d to signal the end of my sessions. I wanted something that would allow me to finish my flow state, but still prompt me to take regular breaks, ideally around every 25 minutes. I believe the brain doesn\u2019t operate in fixed time intervals. It seems to have its own natural rhythm and desire to work. I don\u2019t want to interfere with that, but I also don\u2019t want to let it run for too long. I want to give it time to \u201ccool down.\u201d<\/p>\n<blockquote class=\"twitter-tweet\"><p lang=\"en\" dir=\"ltr\">I&#39;ve made myself a 25minutes playlist in spotify. Start work, \u25b6\ufe0f the music, music stops \u23f9\ufe0f, stop work and take a break, then repeat. <a href=\"https:\/\/twitter.com\/hashtag\/pomodorotechnique?src=hash&amp;ref_src=twsrc%5Etfw\">#pomodorotechnique<\/a><\/p>&mdash; Ostafi Ion (@i_ostafi) <a href=\"https:\/\/twitter.com\/i_ostafi\/status\/1654089991176302592?ref_src=twsrc%5Etfw\">May 4, 2023<\/a><\/blockquote> <script async src=\"https:\/\/platform.twitter.com\/widgets.js\" charset=\"utf-8\"><\/script>\n<p>I tried using a music-based timer.\nWhen the music stops, I start to notice background noise. In the office, it\u2019s people talking, fans running. At home, it\u2019s pure silence.\nAfter a few minutes, I slip out of the flow, and my brain realizes the music has stopped\u2014Oh, I need to take a break.\nThis can still go out of control, as I can go so deep into focus state that I am unable to hear anything even if there\nis a building crashing nearby. But that is unfixable by any timer or be even a person nearby yealing at me.<\/p>\n<p>One day, I got tired of the same playlist.\nIt didn\u2019t work for long, so I found a simple Mac app\u2014Pomodoro Timer\u2014that does part of what I wanted.\nI still use the app today, and it works for me.\nI can get into that little moment of \u201cWait, the music stopped, time for a break.\u201d\nBut there\u2019s a piece missing from the puzzle, you know.\nA perfectly timed music session, synced with my work session\u2014where the last song plays until the very end.\nDoes that make sense? \ud83d\ude42 Probably not, but it\u2019s fun!<\/p>\n<p>The engineer in me couldn\u2019t resist thinking about a solution.\nHaha, I took this so seriously that I started searching for an algorithm to generate the perfect 25-minute playlist.\nI didn\u2019t even realize that the problem I was trying to solve is an unsolved math problem\u2014the subset sum problem (<a href=\"https:\/\/en.wikipedia.org\/wiki\/Subset_sum_problem\">Wikipedia<\/a>).\nWhat does the subset sum problem have to do with a playlist?\nFrom a playlist of N songs, you need to find a sub-playlist of M songs that adds up to exactly 25 minutes.<\/p>\n<p>\u00a3\u00a3\\sum_1^n seconds(song(n)) = 1500\u00a3\u00a3<\/p>\n<p>Now, I\u2019m developing my own iOS app to generate the perfect Pomodoro playlist for each session.\nBut I can\u2019t just throw something together\u2014I have to craft it with a carefully designed architecture,\nputting all my knowledge into this piece of software.\nWhat\u2019s the point of reading books like Software Architecture in Practice or Code Complete if it all just stays theoretical?\nI want to try even the wildest ideas I come across into practice and see how they work in the real world.<\/p>\n<p>I named the app M25, which stands for Music for 25 Minutes. Alongside developing the app,\nI plan to document the entire development process\u2014covering everything from choosing software design patterns and refactoring code to switching development tools.\nI\u2019m considering creating a series of articles that showcase how to implement the Model-View-ViewModel (MVVM) architecture in iOS development,\nor explore other mobile app architectures.\nI\u2019ll also demonstrate how to use design patterns like the observer pattern and others.<\/p>\n<p>The goal is to show how to take a software project from zero to production,\nfocusing on best practices for building clean, maintainable codebases.\nIt\u2019s not just about writing an app quickly,\nbut about leveraging professional development techniques and architectural knowledge.<\/p>\n<p>Continue reading <a href=\"..\/ios-event-driven-architecture\">about architecture of the project<\/a><\/p>\n"},{"title":"Architecture | Image assets","pubDate":"Wed, 08 Nov 2023 00:00:00 +0000","author":"Ion Ostafi","link":"https:\/\/ionostafi.com\/blog\/assets-ios-naming\/","guid":"https:\/\/ionostafi.com\/blog\/assets-ios-naming\/","description":"<h2 id=\"intro\">Intro<\/h2>\n<p>In many large mobile projects, a variety of pictures, both small and large, are commonly used within the app. As more images are added to the project, it becomes necessary to organize them effectively. However, it is common for developers to overlook proper organization and simply place them in a folder or group them without much thought.<\/p>\n<h2 id=\"the-default-method\">The default method<\/h2>\n<p>A common method I have observed is categorizing and labeling them according to their features and usage. This approach aligns with our natural thinking process. Supporters of this method argue that it allows for easy icon switching without requiring code updates, only image changes. However, is this truly advantageous, or is updating the name really a significant issue?<\/p>\n<h2 id=\"the-problem-with-feature-based-naming-for-image-assets\">The problem with feature based naming for image assets<\/h2>\n<ol>\n<li><strong>Duplication<\/strong>: In larger projects, people naturally group everything per feature, including image assets. These groups are created based on existing features. As features grow and designers start to reuse icons in different parts of the project, engineers may not go through the trouble of moving images from one feature group to another or renaming assets. It is often easier and faster to simply refer to an existing image from another feature and continue working.<\/li>\n<li><strong>Nesting<\/strong>: Big features can be easier to reason about when they are split into smaller sub-features. Therefore, it might seem that organizing images into sub-folders would be simpler, but it is not unless you establish clear rules and constraints for organizing common assets outside of sub-feature folders.<\/li>\n<\/ol>\n<h2 id=\"the-three-big-groups-icons-graphics-and-backgrounds\">The three big groups: Icons, Graphics, and Backgrounds<\/h2>\n<p>The following approach is one way my team is using in production to manage image assets. I came up with this after realizing that our app had become very disorganized with its assets.<\/p>\n<ol>\n<li><strong>Icons<\/strong>: To adhere to the content-based naming approach, name each image according to its content. For example, if an image depicts a crown and has a size of 1x scale with a measurement of 40, the appropriate name would be \u201ccrown_40.png.\u201d<\/li>\n<li><strong>Graphics<\/strong>: They contain larger images that are used less frequently than icons, and could depict a character, a company logo, an object, or similar. For instance, the image\u2019s name could be \u201cletter_sparks_120x100.png,\u201d representing a letter with sparks around it, and it would be used only in a specific location within the app.<\/li>\n<li><strong>Backgrounds<\/strong>: This section contains large images primarily used as backgrounds, but it is not limited to that purpose. These images can also be placed between sections or above other elements. An example of a background image name would be \u201crobot_arm_circles_1200x800.png\u201d, which depicts a large mechanical arm with circles in the background.<\/li>\n<\/ol>\n<h2 id=\"advantage-of-the-three-groups\">Advantage of the three groups<\/h2>\n<p>This approach makes it easier to detect duplication, optimize assets, and even identify similar images with small differences. These images can be sent to the design team for review, to determine if they need those similar images or if they should keep just one. As opposed to a feature-based organization, it simplifies the decision-making process of where to place the image asset, eliminating the need to update the location later if the image needs to be shared or if a feature disappears but the image remains.<\/p>\n"},{"title":"Watch Crunchyroll Anime Together with Apple SharePlay","pubDate":"Fri, 04 Nov 2022 00:00:00 +0000","author":"Ion Ostafi","link":"https:\/\/ionostafi.com\/crunchyroll\/shareplay-at-crunchyroll\/","guid":"https:\/\/ionostafi.com\/crunchyroll\/shareplay-at-crunchyroll\/","description":"<p>At WWDC21, Apple presented a new technology for doing more things together with your friends and family \u2014 SharePlay. It allows us to watch, draw, or even play games together. This piece of technology can be used in various ways. I\u2019ll go through the implementation of SharePlay for watching your favorite anime.<\/p>\n<p><strong>Before Digging In, Understand Basic Terms<\/strong><\/p>\n<p><a href=\"https:\/\/developer.apple.com\/documentation\/groupactivities\">GroupActivities<\/a> \u2014 the framework that makes it possible to implement the SharePlay feature.<\/p>\n<p><strong>GroupActivities session<\/strong> \u2014 an ongoing connection between one or more devices communicating using a session on the server.<\/p>\n<p>GroupActivities works on top of a FaceTime call. The devices are synched only when the participants are on an active call. And a GroupActivity session can be started only when the device is on a FaceTime call.<\/p>\n<p>The diagram (IMG 1) below shows an overview of how a SharePlay session is created and how participants join the session:<\/p>\n<p><img src=\"https:\/\/ionostafi.com\/crunchyroll\/shareplay-at-crunchyroll\/.\/overview_of_the_shareplay_session_creation.webp\" alt=\"Overview of the SharePlay session creation\" \/><\/p>\n<p><strong>The SharePlay Experience Inside Crunchyroll<\/strong><\/p>\n<p>The app needs to know when the participant is on a FaceTime call, so it can indicate that SharePlay is possible by displaying the SharePlay icon under the series title and the \u201cStart SharePlay\u201d button on the video page. Anyone can start a SharePlay session from the following places (IMG 2):<\/p>\n<ul>\n<li>The video page;<\/li>\n<li>The more [\u2807] menu of any card;<\/li>\n<li>The long press (3D Touch) of any card;<\/li>\n<li>The ShareSheet of an episode.<\/li>\n<\/ul>\n<p><img src=\"https:\/\/ionostafi.com\/crunchyroll\/shareplay-at-crunchyroll\/.\/an_example_of_three_entry_points_to_SharePlay.webp\" alt=\"An example of three entry points to SharePlay\" \/><\/p>\n<p>If another participant has a membership, they will be directed to that episode after joining the session.<\/p>\n<p>While switching to a different episode, a popup asks for episode switching confirmation, and after confirming, it switches to the new episode.<\/p>\n<p>When someone leaves the video page, a popup asks for leaving confirmation; the current participant can choose to end the session for everyone or only for themselves (IMG 3).<\/p>\n<p><img src=\"https:\/\/ionostafi.com\/crunchyroll\/shareplay-at-crunchyroll\/.\/Switching_to_another_episode_left_and_closing_the_video_player_right.webp\" alt=\"Switching to another episode (left) and closing the video player (right)\" \/><\/p>\n<p><strong>Determine eligibility to start SharePlay<\/strong><\/p>\n<p>It\u2019s possible using <a href=\"https:\/\/developer.apple.com\/documentation\/groupactivities\/groupstateobserver\/iseligibleforgroupsession\">GroupStateObserver<\/a> class.<\/p>\n<p><img src=\"https:\/\/ionostafi.com\/crunchyroll\/shareplay-at-crunchyroll\/.\/Determine_eligibility_to_start_SharePlay.webp\" alt=\"Determine_eligibility_to_start_SharePlay\" \/><\/p>\n<p>We keep only one instance of GroupStateObserver in the app for the whole lifetime of the app. We will subscribe to the GroupStateObserver\u2019s idEligibleForGroupSession stream and on each change, we will show\/hide the SharePlay icon and SharePlay button.<\/p>\n<p><strong>Starting a new session<\/strong><\/p>\n<p>The participant who starts a session does not join automatically, we should join programmatically. See in the overview diagram (IMG 1) that the participant who starts the session will later receive a session from the server, the same as other participants.<\/p>\n<p>Follow these steps to create a new session:<\/p>\n<p><img src=\"https:\/\/ionostafi.com\/crunchyroll\/shareplay-at-crunchyroll\/.\/Start_a_session.webp\" alt=\"Start_a_session\" \/><\/p>\n<p>Calling prepareForActivation will tell the system to ask either to play this item on the device or SharePlay the episode.<\/p>\n<p><img src=\"https:\/\/ionostafi.com\/crunchyroll\/shareplay-at-crunchyroll\/.\/SharePlay_1st_button_will_start_the_session_Start_Only_for_Me_2nd_button_will_play_video_only_on_the_user_device.webp\" alt=\"SharePlay_1st_button_will_start_the_session_Start_Only_for_Me_2nd_button_will_play_video_only_on_the_user_device\" \/><\/p>\n<p>Later, if the user chooses to start automatically SharePlay, then calling this function will choose SharePlay automatically. Based on the prepareForActivation result, it\u2019s our responsibility to start the SharePlay session by calling activate a function that will start the session itself.<\/p>\n<p>This is it for creating a session. The upper steps will not automatically join the session! The activate function creates a session on the \u201cserver\u201d, and it sends that session to all FaceTime participants. This is important to understand and not to be confused later why the user who started SharePlay is receiving the \u201cjoin event\u201d too.<\/p>\n<p><strong>Joining the session<\/strong><\/p>\n<p>Next, if we want to join the session, either created by the current participant or someone else, we have to write the same thing in both cases:<\/p>\n<p><img src=\"https:\/\/ionostafi.com\/crunchyroll\/shareplay-at-crunchyroll\/.\/join_a_session.webp\" alt=\"join_a_session\" \/><\/p>\n<p>The upper code is simplified, and the actual code is more complex than that: verify if a deep link is in progress, wait for the episode data to load, and other things.<\/p>\n<p><strong>Synchronizing video players for all participants<\/strong><\/p>\n<p>Now, we will cover the most important aspect\u2014 control playback for all participants. For this to happen, it\u2019s not enough to join a session. The session is just a channel to send data; until this point, we just set up the connection between participants. From now on, we will be able to transmit information between participants.<\/p>\n<p>To synchronize the player, we use the new <a href=\"https:\/\/developer.apple.com\/documentation\/avfoundation\/avplayerplaybackcoordinator\">playback coordination API<\/a>. We need to link the session to the player. This is achieved using the following:<\/p>\n<p><img src=\"https:\/\/ionostafi.com\/crunchyroll\/shareplay-at-crunchyroll\/.\/Synchronize_events.webp\" alt=\"Synchronize_events\" \/><\/p>\n<p>After connecting the player with the session, the player automatically sends all events, like play, pause, or seek, to all participants.<\/p>\n<p><strong>Replacing the episode<\/strong><\/p>\n<p>There are two different scenarios to replace an episode in the Crunchyroll app:<\/p>\n<ul>\n<li>when the participant is manually switching an episode and is asked for confirmation before replacing;<\/li>\n<li>when all participants automatically switch to the next episode, and there is no confirmation.<\/li>\n<\/ul>\n<p>If all participants are in the middle of watching an episode, and one participant wants to switch to another, execute the same code as when starting a new session. GroupActivity API understands that a session was already created, and this time will switch only the content, and not create another session. It will ask the participant to confirm the content replacement with the following screen:<\/p>\n<p><img src=\"https:\/\/ionostafi.com\/crunchyroll\/shareplay-at-crunchyroll\/.\/Replace_an_episode.webp\" alt=\"Replace_an_episode\" \/><\/p>\n<p>If all participants finish watching an episode, the Crunchyroll app can advance to the next episode automatically (if at least one participant has this option turned on). In this case, we need to switch the video programmatically without asking for confirmation. To do that, set the currentActivity property on the session object directly.<\/p>\n<p><img src=\"https:\/\/ionostafi.com\/crunchyroll\/shareplay-at-crunchyroll\/.\/Replace_the_current_episode.webp\" alt=\"Replace_the_current_episode\" \/><\/p>\n<p><strong>Interruptions<\/strong><\/p>\n<p>There might be situations when the video should be paused only for one participant and later be advanced to the same time as other participants. A phone call or other system events will automatically pause synchronization for the current user. But in case there are some events triggered by the Crunchyroll app that should pause the video, Apple provides an API for this case. For example, the Crunchyroll app will show an alert when a participant who is watching a video switches connections between wi-fi and cellular.<\/p>\n<p>Pausing video in such case is called \u201cinterruption\u201d, and to interrupt the video, we use the following method call:<\/p>\n<p><img src=\"https:\/\/ionostafi.com\/crunchyroll\/shareplay-at-crunchyroll\/.\/Interrupt_video_for_current_participant.webp\" alt=\"Interrupt_video_for_current_participant\" \/><\/p>\n<p>Notice that beginSuspension is returning a suspension object which we save for later use.<\/p>\n<p>Later, we have to resume playback and move the participant\u2019s playback to the same time as others. To achieve that, use the following:<\/p>\n<p><img src=\"https:\/\/ionostafi.com\/crunchyroll\/shareplay-at-crunchyroll\/.\/Resume_the_interruption_for_the_current_participant.webp\" alt=\"Resume_the_interruption_for_the_current_participant\" \/><\/p>\n<p><strong>ShareSheet<\/strong><\/p>\n<p>With iOS 15.4 \u2014 Apple added the possibility to start SharePlay from the ShareSheet. Apple added some new options to make it easier to share your loved episode with friends over SharePlay. One of the new features of the ShareSheet is prominent activity \u2014 a new section on top of the ShareSheet that displays only one activity, for example, SharePlay, to the user. With this new feature, we can start a FaceTime call and SharePlay with only one button.<\/p>\n<p><img src=\"https:\/\/ionostafi.com\/crunchyroll\/shareplay-at-crunchyroll\/.\/Prominent_activity_in_iOS_15.4.webp\" alt=\"Prominent_activity_in_iOS_15\" \/><\/p>\n<p>By default, the SharePlay from the ShareSheet doesn\u2019t know how to start a session or which item to send through the session, and it will simply start a FaceTime call and create an empty session without any activity item (episode).<\/p>\n<p>To have better support for SharePlay with the ShareSheet, we need a few lines of code. Do you remember how we created a new activity when we needed to start a new session? Well, here we create an activity the same way, but to make it available for the ShareSheet, we need to assign it to the list of activities from the UIActivityViewController, and here\u2019s how:<\/p>\n<p><img src=\"https:\/\/ionostafi.com\/crunchyroll\/shareplay-at-crunchyroll\/.\/Setup_ShareSheet_with_a_SharePlaySessionActivity_together_with_an_URL.webp\" alt=\"Setup_ShareSheet_with_a_SharePlaySessionActivity_together_with_an_URL\" \/><\/p>\n<p>The important thing here is that we need to create a NSItemProvider, the standard way to send data across processes in iOS. New to iOS 15.4, NSItemProvider has a method to register a GroupActivity.<\/p>\n<p><strong>End notes<\/strong><\/p>\n<p>Adding SharePlay into the application isn\u2019t the most straightforward task, but it\u2019s not that complicated. Follow the WWDC sessions and the sample code from Apple, which will teach you the basics you need.<\/p>\n<p>Some features were not documented well enough in the beginning, for example, <code>requestForegroundPresentation<\/code> method. Initially, the documentation was empty.<\/p>\n<p>When iOS 15.4 came out, it wasn\u2019t straightforward to add support for SharePlay together with a URL in the ShareSheet. We had to figure it out ourselves because there was no tutorial or sample code for making this.<\/p>\n"},{"title":"iOS | UIKit | Large title","pubDate":"Mon, 28 Dec 2020 00:00:00 +0000","author":"Ion Ostafi","link":"https:\/\/ionostafi.com\/blog\/two-title-nav-bar\/","guid":"https:\/\/ionostafi.com\/blog\/two-title-nav-bar\/","description":"<ul>\n<li><a href=\"https:\/\/ionostafi.com\/blog\/two-title-nav-bar\/#background\">Background<\/a><\/li>\n<li><a href=\"https:\/\/ionostafi.com\/blog\/two-title-nav-bar\/#community-solutions\">Community solutions<\/a><\/li>\n<li><a href=\"https:\/\/ionostafi.com\/blog\/two-title-nav-bar\/#reverse-engineering\">Reverse engineering<\/a><\/li>\n<li><a href=\"https:\/\/ionostafi.com\/blog\/two-title-nav-bar\/#demo-project\">Demo project<\/a><\/li>\n<li><a href=\"https:\/\/ionostafi.com\/blog\/two-title-nav-bar\/#the-solution\">The Solution<\/a><\/li>\n<li><a href=\"https:\/\/ionostafi.com\/blog\/two-title-nav-bar\/#notes\">Notes<\/a>\n<ul>\n<li><a href=\"https:\/\/ionostafi.com\/blog\/two-title-nav-bar\/#good\">Good<\/a><\/li>\n<li><a href=\"https:\/\/ionostafi.com\/blog\/two-title-nav-bar\/#bad\">Bad<\/a><\/li>\n<\/ul>\n<\/li>\n<\/ul>\n<h2 id=\"background\">Background<\/h2>\n<p>Back in iOS 11, Apple introduced the <strong>Large Title<\/strong> feature, which became the usual UI for navigation bars. UIKit framework provides a <a href=\"https:\/\/developer.apple.com\/documentation\/uikit\/uinavigationbar\/2908999-preferslargetitles\">simple way<\/a> to enable the new shiny feature. <strong>But<\/strong>, there is a missing piece in the API: <strong>We can\u2019t make a Large title to have two lines of text<\/strong> (<em>or do we?<\/em>)<\/p>\n<h2 id=\"community-solutions\">Community solutions<\/h2>\n<p>If Apple didn\u2019t add a way to make two lines large titles, developers made their way to solve the problem. On <a href=\"https:\/\/stackoverflow.com\/questions\/47901318\/how-to-set-multi-line-large-title-in-navigation-bar-new-feature-of-ios-11\">this stackoverflow<\/a> page, there are multiple solutions, which don\u2019t work in iOS 15.<\/p>\n<p><a href=\"https:\/\/developer.apple.com\/forums\/profile\/khurshedgulov\">khurshedgulov<\/a> asked in <a href=\"https:\/\/developer.apple.com\/forums\/thread\/671982\">apple developer forums<\/a> how to make large titles like <strong>Apple is doing in App Store app<\/strong>. Unfortunately, no one from Apple responded.<\/p>\n<p>There are at least two apps from Apple that are using two lines for Large Titles: <em>App Store<\/em>, <em>Watch<\/em>.<\/p>\n<h2 id=\"reverse-engineering\">Reverse engineering<\/h2>\n<p>I was confident that there should be a hidden way to enable this feature. <strong>Let\u2019s dig \u26cf inside UIKit<\/strong><\/p>\n<p>Based on the <a href=\"https:\/\/stackoverflow.com\/questions\/47901318\/how-to-set-multi-line-large-title-in-navigation-bar-new-feature-of-ios-11\">stackoverflow<\/a> answers, the starting point was to look into the view structure of <code>NavigationBar<\/code> itself.<\/p>\n<p>I created a subclass to <code>NavigationBar<\/code> and put a breakpoint in the function: <code>didAddSubview<\/code>. I inspected every subview coming as an input parameter to this function. From all subviews, one is named <code>_UINavigationBarLargeTitleView<\/code> (a private Apple class), and it has a private var named <code>_twoLineMode<\/code> with a value of <code>0<\/code> (turned off)!<\/p>\n<p>Two Line Mode - it is there and I just needed a way to turn it on.<\/p>\n<p><img src=\"https:\/\/ionostafi.com\/blog\/two-title-nav-bar\/.\/_UINavigationBarLargeTitleView.png\" alt=\"private-class\" \/><\/p>\n<p>I tried this<\/p>\n<pre data-lang=\"swift\" class=\"language-swift z-code\"><code class=\"language-swift\" data-lang=\"swift\"><span class=\"z-source z-swift\">subview<span class=\"z-keyword z-operator z-custom z-postfix z-unary z-swift\">.<\/span>setValue(<span class=\"z-constant z-numeric z-integer z-decimal z-swift\">1<\/span>, forKey: <span class=\"z-meta z-literal z-string z-swift\"><span class=\"z-string z-quoted z-double z-swift\">&quot;<\/span><span class=\"z-string z-quoted z-double z-swift\">_<\/span><span class=\"z-string z-quoted z-double z-swift\">t<\/span><span class=\"z-string z-quoted z-double z-swift\">w<\/span><span class=\"z-string z-quoted z-double z-swift\">o<\/span><span class=\"z-string z-quoted z-double z-swift\">L<\/span><span class=\"z-string z-quoted z-double z-swift\">i<\/span><span class=\"z-string z-quoted z-double z-swift\">n<\/span><span class=\"z-string z-quoted z-double z-swift\">e<\/span><span class=\"z-string z-quoted z-double z-swift\">M<\/span><span class=\"z-string z-quoted z-double z-swift\">o<\/span><span class=\"z-string z-quoted z-double z-swift\">d<\/span><span class=\"z-string z-quoted z-double z-swift\">e<\/span><span class=\"z-string z-quoted z-double z-swift\">&quot;<\/span><\/span>)\n<\/span><\/code><\/pre>\n<p>I tried to set the value in the <code>didAddSubview<\/code> and <code>willAddSubview<\/code> functions. None worked \ud83d\ude29, the value was reset somewhere after view was added as subview. After long inspecting and playing around with different variables of the <code>_UINavigationBarLargeTitleView<\/code> object, I couldn\u2019t make it work.<\/p>\n<p>I needed to find which object is controlling the <code>_twoLineMode<\/code> var.<\/p>\n<p><code>UINavigationBar<\/code> is constructed using <code>UINavigationItem<\/code>s. To inspect the item, I created a subclass to <code>UINavigationController<\/code> and overrode function <code>navigationBar(_:shouldPush:)<\/code> which is a function for <code>UINavigationBar<\/code>\u2019s delegate. After inspecting this object, I <strong>Found another clue!<\/strong> Another private var named <code>__largeTitleTwoLineMode<\/code>, again, with a value of <code>0<\/code>.\n<img src=\"https:\/\/ionostafi.com\/blog\/two-title-nav-bar\/__largeTitleTwoLineMode.png\" alt=\"__largeTitleTwoLineMode\" \/><\/p>\n<p>I set this var to <code>1<\/code> or <code>true<\/code> and <strong>HERE IT IS!<\/strong>. I had a Large Title with two lines \ud83d\ude4c!<\/p>\n<pre data-lang=\"swift\" class=\"language-swift z-code\"><code class=\"language-swift\" data-lang=\"swift\"><span class=\"z-source z-swift\">item<span class=\"z-keyword z-operator z-custom z-postfix z-unary z-swift\">.<\/span>setValue(<span class=\"z-constant z-numeric z-integer z-decimal z-swift\">1<\/span>, forKey: <span class=\"z-meta z-literal z-string z-swift\"><span class=\"z-string z-quoted z-double z-swift\">&quot;<\/span><span class=\"z-string z-quoted z-double z-swift\">_<\/span><span class=\"z-string z-quoted z-double z-swift\">_<\/span><span class=\"z-string z-quoted z-double z-swift\">l<\/span><span class=\"z-string z-quoted z-double z-swift\">a<\/span><span class=\"z-string z-quoted z-double z-swift\">r<\/span><span class=\"z-string z-quoted z-double z-swift\">g<\/span><span class=\"z-string z-quoted z-double z-swift\">e<\/span><span class=\"z-string z-quoted z-double z-swift\">T<\/span><span class=\"z-string z-quoted z-double z-swift\">i<\/span><span class=\"z-string z-quoted z-double z-swift\">t<\/span><span class=\"z-string z-quoted z-double z-swift\">l<\/span><span class=\"z-string z-quoted z-double z-swift\">e<\/span><span class=\"z-string z-quoted z-double z-swift\">T<\/span><span class=\"z-string z-quoted z-double z-swift\">w<\/span><span class=\"z-string z-quoted z-double z-swift\">o<\/span><span class=\"z-string z-quoted z-double z-swift\">L<\/span><span class=\"z-string z-quoted z-double z-swift\">i<\/span><span class=\"z-string z-quoted z-double z-swift\">n<\/span><span class=\"z-string z-quoted z-double z-swift\">e<\/span><span class=\"z-string z-quoted z-double z-swift\">M<\/span><span class=\"z-string z-quoted z-double z-swift\">o<\/span><span class=\"z-string z-quoted z-double z-swift\">d<\/span><span class=\"z-string z-quoted z-double z-swift\">e<\/span><span class=\"z-string z-quoted z-double z-swift\">&quot;<\/span><\/span>)\n<\/span><span class=\"z-source z-swift\"><span class=\"z-comment z-line z-double-slash z-swift\"><span class=\"z-punctuation z-definition z-comment z-line z-double-slash z-swift\">\/\/<\/span> OR<\/span>\n<\/span><span class=\"z-source z-swift\">item<span class=\"z-keyword z-operator z-custom z-postfix z-unary z-swift\">.<\/span>setValue(<span class=\"z-keyword z-constant z-boolean z-swift\">true<\/span>, forKey: <span class=\"z-meta z-literal z-string z-swift\"><span class=\"z-string z-quoted z-double z-swift\">&quot;<\/span><span class=\"z-string z-quoted z-double z-swift\">_<\/span><span class=\"z-string z-quoted z-double z-swift\">_<\/span><span class=\"z-string z-quoted z-double z-swift\">l<\/span><span class=\"z-string z-quoted z-double z-swift\">a<\/span><span class=\"z-string z-quoted z-double z-swift\">r<\/span><span class=\"z-string z-quoted z-double z-swift\">g<\/span><span class=\"z-string z-quoted z-double z-swift\">e<\/span><span class=\"z-string z-quoted z-double z-swift\">T<\/span><span class=\"z-string z-quoted z-double z-swift\">i<\/span><span class=\"z-string z-quoted z-double z-swift\">t<\/span><span class=\"z-string z-quoted z-double z-swift\">l<\/span><span class=\"z-string z-quoted z-double z-swift\">e<\/span><span class=\"z-string z-quoted z-double z-swift\">T<\/span><span class=\"z-string z-quoted z-double z-swift\">w<\/span><span class=\"z-string z-quoted z-double z-swift\">o<\/span><span class=\"z-string z-quoted z-double z-swift\">L<\/span><span class=\"z-string z-quoted z-double z-swift\">i<\/span><span class=\"z-string z-quoted z-double z-swift\">n<\/span><span class=\"z-string z-quoted z-double z-swift\">e<\/span><span class=\"z-string z-quoted z-double z-swift\">M<\/span><span class=\"z-string z-quoted z-double z-swift\">o<\/span><span class=\"z-string z-quoted z-double z-swift\">d<\/span><span class=\"z-string z-quoted z-double z-swift\">e<\/span><span class=\"z-string z-quoted z-double z-swift\">&quot;<\/span><\/span>)\n<\/span><\/code><\/pre>\n<p><img src=\"https:\/\/ionostafi.com\/blog\/two-title-nav-bar\/.\/TwoLinesLargeTitle.png\" alt=\"TwoLinesLargeTitle\" \/><\/p>\n<h2 id=\"demo-project\">Demo project<\/h2>\n<p>I created a demo project named <a href=\"https:\/\/github.com\/BProg\/NavBarLargeTitle\">NavBarLargeTitle<\/a>. The project will list Swift Language Evolution proposals inside the first <code>UIViewController<\/code> and details in the second. It target iOS 15 and uses some iOS 14 features for configuring the <code>UITableView<\/code> like <a href=\"https:\/\/developer.apple.com\/documentation\/uikit\/uitableviewcell\/3601058-defaultcontentconfiguration\">cell configuration<\/a><\/p>\n<h2 id=\"the-solution\">The Solution<\/h2>\n<ol>\n<li>Create a custom <code>UINavigationController<\/code><\/li>\n<li>Add the protocol <code>UINavigationBarDelegate<\/code> to the class definition<\/li>\n<li>Override the function <code>navigationBar(_:shouldPush:)<\/code><\/li>\n<li>Activate two lines mode using hidden variable <code>item.setValue(true, forKey: \"__largeTitleTwoLineMode\")<\/code><\/li>\n<li>Make <code>navigationController.navigationBar.prefersLargeTitles = true<\/code><\/li>\n<\/ol>\n<h2 id=\"notes\">Notes<\/h2>\n<p>I haven\u2019t tested every possible way to set the hidden <code>__largeTitleTwoLineMode<\/code> variable, and possibly, variable could be set in any place before the item is added to the <code>UINavigationBar<\/code><\/p>\n<h3 id=\"good\">Good<\/h3>\n<p>Compatibility - the current solution works at least with iOS 15, 14, 13<\/p>\n<h3 id=\"bad\">Bad<\/h3>\n<p>Animation - the interactive back animation is not perfect in the demo project, I haven\u2019t gone further to dig into this problem.<\/p>\n<p>Unreliable - we can\u2019t rely on Apple\u2019s hidden API because it can break with any new release. But the good thing, is that current solution is so simple that it can easily be updated in such a scenario.<\/p>\n"},{"title":"Design | Decorator pattern","pubDate":"Mon, 03 Dec 2018 00:00:00 +0000","author":"Ion Ostafi","link":"https:\/\/ionostafi.com\/blog\/decorator\/","guid":"https:\/\/ionostafi.com\/blog\/decorator\/","description":"<h3 id=\"intro\">Intro<\/h3>\n<p>In this post, you will see yet another implementation of the decorator pattern. This is a real implementation I used in a project, but here, I reduced and simplified the code. Imagine you don\u2019t have any css\/html, UIKit, or QT framework and need to implement an UI system. In this simple post, you will implement a simple button rendering system based on OOP pattern: <code>Decorator<\/code>.<\/p>\n<p>Possible situations<\/p>\n<ul>\n<li>Button with a text in center and a border\n<img src=\"https:\/\/ionostafi.com\/blog\/decorator\/.\/button_border.png\" alt=\"decorator-pic\" \/><\/li>\n<li>Button with an icon, a text and a border\n<img src=\"https:\/\/ionostafi.com\/blog\/decorator\/.\/button_icon_border.png\" alt=\"decorator-pic\" \/><\/li>\n<li>Button with only a text\n<img src=\"https:\/\/ionostafi.com\/blog\/decorator\/.\/button_no_border.png\" alt=\"decorator-pic\" \/><\/li>\n<li>Kind of a radio button, that has the main title and the radio state title (yes \/ no)\nWhen any of this buttons are focused - background is colored in a color (yellow), border (if any) should disappear, text should change its color to black.\n<img src=\"https:\/\/ionostafi.com\/blog\/decorator\/.\/button_radio_border.png\" alt=\"decorator-pic\" \/><\/li>\n<\/ul>\n<p>Next I will try to implement only a part af those requirements, but the implementation will leave space to extend.<\/p>\n<h3 id=\"decorator-pattern-diagram\">Decorator pattern diagram<\/h3>\n<p>This is the decorator pattern in theory<\/p>\n<p><img src=\"https:\/\/ionostafi.com\/blog\/decorator\/.\/Decorator_pattern.png\" alt=\"decorator-pic\" \/><\/p>\n<h3 id=\"apply-design\">Apply design<\/h3>\n<p>This is how current requirements get designed using decorator pattern<\/p>\n<p><img src=\"https:\/\/ionostafi.com\/blog\/decorator\/.\/Buttons_class.png\" alt=\"decorator-buttons\" \/><\/p>\n<p><em>You can follow in code using https:\/\/www.typescriptlang.org\/play\/. The following code is written in typescript<\/em>.<\/p>\n<h4 id=\"components-used-in-code\">Components used in code<\/h4>\n<p>Secondary components used by buttons and decorator.<\/p>\n<pre data-lang=\"ts\" class=\"language-ts z-code\"><code class=\"language-ts\" data-lang=\"ts\"><span class=\"z-source z-ts\"><span class=\"z-meta z-interface z-ts\"><span class=\"z-storage z-type z-interface z-ts\">interface<\/span> <span class=\"z-entity z-name z-type z-interface z-ts\">Displayable<\/span> <span class=\"z-punctuation z-definition z-block z-ts\">{<\/span>\n<\/span><\/span><span class=\"z-source z-ts\"><span class=\"z-meta z-interface z-ts\"><span class=\"z-meta z-method z-declaration z-ts\">    <span class=\"z-meta z-definition z-method z-ts\"><span class=\"z-entity z-name z-function z-ts\">display<\/span><\/span><span class=\"z-meta z-parameters z-ts\"><span class=\"z-punctuation z-definition z-parameters z-begin z-ts\">(<\/span><span class=\"z-punctuation z-definition z-parameters z-end z-ts\">)<\/span><\/span><\/span><span class=\"z-punctuation z-terminator z-statement z-ts\">;<\/span>\n<\/span><\/span><span class=\"z-source z-ts\"><span class=\"z-meta z-interface z-ts\"><span class=\"z-punctuation z-definition z-block z-ts\">}<\/span><\/span>\n<\/span><span class=\"z-source z-ts\">\n<\/span><span class=\"z-source z-ts\"><span class=\"z-meta z-class z-ts\"><span class=\"z-storage z-type z-class z-ts\">class<\/span> <span class=\"z-entity z-name z-type z-class z-ts\">TextView<\/span> <span class=\"z-storage z-modifier z-ts\">implements<\/span> <span class=\"z-entity z-other z-inherited-class z-ts\">Displayable<\/span> <span class=\"z-punctuation z-definition z-block z-ts\">{<\/span>\n<\/span><\/span><span class=\"z-source z-ts\"><span class=\"z-meta z-class z-ts\"><span class=\"z-meta z-method z-declaration z-ts\">    <span class=\"z-meta z-definition z-method z-ts\"><span class=\"z-entity z-name z-function z-ts\">display<\/span><\/span><span class=\"z-meta z-parameters z-ts\"><span class=\"z-punctuation z-definition z-parameters z-begin z-ts\">(<\/span><span class=\"z-punctuation z-definition z-parameters z-end z-ts\">)<\/span><\/span> <span class=\"z-meta z-block z-ts\"><span class=\"z-punctuation z-definition z-block z-ts\">{<\/span>\n<\/span><\/span><\/span><\/span><span class=\"z-source z-ts\"><span class=\"z-meta z-class z-ts\"><span class=\"z-meta z-method z-declaration z-ts\"><span class=\"z-meta z-block z-ts\">        <span class=\"z-meta z-function-call z-ts\"><span class=\"z-support z-class z-console z-ts\">console<\/span><span class=\"z-punctuation z-accessor z-ts\">.<\/span><span class=\"z-support z-function z-console z-ts\">log<\/span><\/span><span class=\"z-meta z-brace z-round z-ts\">(<\/span><span class=\"z-string z-quoted z-double z-ts\"><span class=\"z-punctuation z-definition z-string z-begin z-ts\">&quot;<\/span>&lt;TextView&gt;<span class=\"z-punctuation z-definition z-string z-end z-ts\">&quot;<\/span><\/span><span class=\"z-meta z-brace z-round z-ts\">)<\/span><span class=\"z-punctuation z-terminator z-statement z-ts\">;<\/span>\n<\/span><\/span><\/span><\/span><span class=\"z-source z-ts\"><span class=\"z-meta z-class z-ts\"><span class=\"z-meta z-method z-declaration z-ts\"><span class=\"z-meta z-block z-ts\">    <span class=\"z-punctuation z-definition z-block z-ts\">}<\/span><\/span><\/span><span class=\"z-punctuation z-terminator z-statement z-ts\">;<\/span>\n<\/span><\/span><span class=\"z-source z-ts\"><span class=\"z-meta z-class z-ts\"><span class=\"z-punctuation z-definition z-block z-ts\">}<\/span><\/span>\n<\/span><span class=\"z-source z-ts\">\n<\/span><span class=\"z-source z-ts\"><span class=\"z-meta z-class z-ts\"><span class=\"z-storage z-type z-class z-ts\">class<\/span> <span class=\"z-entity z-name z-type z-class z-ts\">Picture<\/span> <span class=\"z-storage z-modifier z-ts\">implements<\/span> <span class=\"z-entity z-other z-inherited-class z-ts\">Displayable<\/span> <span class=\"z-punctuation z-definition z-block z-ts\">{<\/span>\n<\/span><\/span><span class=\"z-source z-ts\"><span class=\"z-meta z-class z-ts\"><span class=\"z-meta z-method z-declaration z-ts\">    <span class=\"z-meta z-definition z-method z-ts\"><span class=\"z-entity z-name z-function z-ts\">display<\/span><\/span><span class=\"z-meta z-parameters z-ts\"><span class=\"z-punctuation z-definition z-parameters z-begin z-ts\">(<\/span><span class=\"z-punctuation z-definition z-parameters z-end z-ts\">)<\/span><\/span> <span class=\"z-meta z-block z-ts\"><span class=\"z-punctuation z-definition z-block z-ts\">{<\/span>\n<\/span><\/span><\/span><\/span><span class=\"z-source z-ts\"><span class=\"z-meta z-class z-ts\"><span class=\"z-meta z-method z-declaration z-ts\"><span class=\"z-meta z-block z-ts\">        <span class=\"z-meta z-function-call z-ts\"><span class=\"z-support z-class z-console z-ts\">console<\/span><span class=\"z-punctuation z-accessor z-ts\">.<\/span><span class=\"z-support z-function z-console z-ts\">log<\/span><\/span><span class=\"z-meta z-brace z-round z-ts\">(<\/span><span class=\"z-string z-quoted z-double z-ts\"><span class=\"z-punctuation z-definition z-string z-begin z-ts\">&quot;<\/span>&lt;Picture&gt;<span class=\"z-punctuation z-definition z-string z-end z-ts\">&quot;<\/span><\/span><span class=\"z-meta z-brace z-round z-ts\">)<\/span>\n<\/span><\/span><\/span><\/span><span class=\"z-source z-ts\"><span class=\"z-meta z-class z-ts\"><span class=\"z-meta z-method z-declaration z-ts\"><span class=\"z-meta z-block z-ts\">    <span class=\"z-punctuation z-definition z-block z-ts\">}<\/span><\/span><\/span><span class=\"z-punctuation z-terminator z-statement z-ts\">;<\/span>\n<\/span><\/span><span class=\"z-source z-ts\"><span class=\"z-meta z-class z-ts\"><span class=\"z-punctuation z-definition z-block z-ts\">}<\/span><\/span>\n<\/span><span class=\"z-source z-ts\">\n<\/span><span class=\"z-source z-ts\"><span class=\"z-meta z-class z-ts\"><span class=\"z-storage z-type z-class z-ts\">class<\/span> <span class=\"z-entity z-name z-type z-class z-ts\">Box<\/span> <span class=\"z-storage z-modifier z-ts\">implements<\/span> <span class=\"z-entity z-other z-inherited-class z-ts\">Displayable<\/span> <span class=\"z-punctuation z-definition z-block z-ts\">{<\/span>\n<\/span><\/span><span class=\"z-source z-ts\"><span class=\"z-meta z-class z-ts\"><span class=\"z-meta z-method z-declaration z-ts\">    <span class=\"z-meta z-definition z-method z-ts\"><span class=\"z-entity z-name z-function z-ts\">display<\/span><\/span><span class=\"z-meta z-parameters z-ts\"><span class=\"z-punctuation z-definition z-parameters z-begin z-ts\">(<\/span><span class=\"z-punctuation z-definition z-parameters z-end z-ts\">)<\/span><\/span> <span class=\"z-meta z-block z-ts\"><span class=\"z-punctuation z-definition z-block z-ts\">{<\/span>\n<\/span><\/span><\/span><\/span><span class=\"z-source z-ts\"><span class=\"z-meta z-class z-ts\"><span class=\"z-meta z-method z-declaration z-ts\"><span class=\"z-meta z-block z-ts\">        <span class=\"z-meta z-function-call z-ts\"><span class=\"z-support z-class z-console z-ts\">console<\/span><span class=\"z-punctuation z-accessor z-ts\">.<\/span><span class=\"z-support z-function z-console z-ts\">log<\/span><\/span><span class=\"z-meta z-brace z-round z-ts\">(<\/span><span class=\"z-string z-quoted z-double z-ts\"><span class=\"z-punctuation z-definition z-string z-begin z-ts\">&quot;<\/span>&lt;Box&gt;<span class=\"z-punctuation z-definition z-string z-end z-ts\">&quot;<\/span><\/span><span class=\"z-meta z-brace z-round z-ts\">)<\/span>\n<\/span><\/span><\/span><\/span><span class=\"z-source z-ts\"><span class=\"z-meta z-class z-ts\"><span class=\"z-meta z-method z-declaration z-ts\"><span class=\"z-meta z-block z-ts\">    <span class=\"z-punctuation z-definition z-block z-ts\">}<\/span><\/span><\/span>\n<\/span><\/span><span class=\"z-source z-ts\"><span class=\"z-meta z-class z-ts\"><span class=\"z-punctuation z-definition z-block z-ts\">}<\/span><\/span>\n<\/span><\/code><\/pre>\n<h4 id=\"abstractbutton\">AbstractButton<\/h4>\n<p>The AbstractComponent class, it is the base for concrete buttons and decorators. BorderButtonDecorator is an AbstractButton, and it sounds strange, this is how this pattern works.<\/p>\n<pre data-lang=\"ts\" class=\"language-ts z-code\"><code class=\"language-ts\" data-lang=\"ts\"><span class=\"z-source z-ts\"><span class=\"z-meta z-class z-ts\"><span class=\"z-storage z-modifier z-ts\">abstract<\/span> <span class=\"z-storage z-type z-class z-ts\">class<\/span> <span class=\"z-entity z-name z-type z-class z-ts\">AbstractButton<\/span> <span class=\"z-storage z-modifier z-ts\">implements<\/span> <span class=\"z-entity z-other z-inherited-class z-ts\">Displayable<\/span> <span class=\"z-punctuation z-definition z-block z-ts\">{<\/span>\n<\/span><\/span><span class=\"z-source z-ts\"><span class=\"z-meta z-class z-ts\">    <span class=\"z-meta z-method z-declaration z-ts\"><span class=\"z-storage z-modifier z-ts\">public<\/span> <span class=\"z-meta z-definition z-method z-ts\"><span class=\"z-entity z-name z-function z-ts\">display<\/span><\/span><span class=\"z-meta z-parameters z-ts\"><span class=\"z-punctuation z-definition z-parameters z-begin z-ts\">(<\/span><span class=\"z-punctuation z-definition z-parameters z-end z-ts\">)<\/span><\/span> <span class=\"z-meta z-block z-ts\"><span class=\"z-punctuation z-definition z-block z-ts\">{<\/span>\n<\/span><\/span><\/span><\/span><span class=\"z-source z-ts\"><span class=\"z-meta z-class z-ts\"><span class=\"z-meta z-method z-declaration z-ts\"><span class=\"z-meta z-block z-ts\">        <span class=\"z-meta z-function-call z-ts\"><span class=\"z-support z-class z-console z-ts\">console<\/span><span class=\"z-punctuation z-accessor z-ts\">.<\/span><span class=\"z-support z-function z-console z-ts\">log<\/span><\/span><span class=\"z-meta z-brace z-round z-ts\">(<\/span><span class=\"z-string z-quoted z-double z-ts\"><span class=\"z-punctuation z-definition z-string z-begin z-ts\">&quot;<\/span>&lt;AbstractButton&gt;<span class=\"z-punctuation z-definition z-string z-end z-ts\">&quot;<\/span><\/span><span class=\"z-meta z-brace z-round z-ts\">)<\/span>\n<\/span><\/span><\/span><\/span><span class=\"z-source z-ts\"><span class=\"z-meta z-class z-ts\"><span class=\"z-meta z-method z-declaration z-ts\"><span class=\"z-meta z-block z-ts\">    <span class=\"z-punctuation z-definition z-block z-ts\">}<\/span><\/span><\/span>\n<\/span><\/span><span class=\"z-source z-ts\"><span class=\"z-meta z-class z-ts\"><span class=\"z-punctuation z-definition z-block z-ts\">}<\/span><\/span>\n<\/span><\/code><\/pre>\n<h4 id=\"pushbutton\">PushButton<\/h4>\n<p>A concrete button, It extends AbstractButton class, and overrides <code>display<\/code> function to render what is specific to it.<\/p>\n<pre data-lang=\"ts\" class=\"language-ts z-code\"><code class=\"language-ts\" data-lang=\"ts\"><span class=\"z-source z-ts\"><span class=\"z-meta z-class z-ts\"><span class=\"z-storage z-type z-class z-ts\">class<\/span> <span class=\"z-entity z-name z-type z-class z-ts\">PushButton<\/span> <span class=\"z-storage z-modifier z-ts\">extends<\/span> <span class=\"z-entity z-other z-inherited-class z-ts\">AbstractButton<\/span> <span class=\"z-punctuation z-definition z-block z-ts\">{<\/span>\n<\/span><\/span><span class=\"z-source z-ts\"><span class=\"z-meta z-class z-ts\">    <span class=\"z-storage z-modifier z-ts\">private<\/span><span class=\"z-meta z-field z-declaration z-ts\"> <span class=\"z-meta z-definition z-property z-ts\"><span class=\"z-variable z-object z-property z-ts\">textView<\/span><\/span><span class=\"z-meta z-type z-annotation z-ts\"><span class=\"z-keyword z-operator z-type z-annotation z-ts\">:<\/span> <span class=\"z-entity z-name z-type z-ts\">TextView<\/span> <\/span><span class=\"z-keyword z-operator z-assignment z-ts\">=<\/span> <span class=\"z-new z-expr z-ts\"><span class=\"z-keyword z-operator z-new z-ts\">new<\/span> <span class=\"z-entity z-name z-type z-ts\">TextView<\/span><span class=\"z-meta z-brace z-round z-ts\">(<\/span><span class=\"z-meta z-brace z-round z-ts\">)<\/span><\/span><\/span><span class=\"z-punctuation z-terminator z-statement z-ts\">;<\/span>\n<\/span><\/span><span class=\"z-source z-ts\"><span class=\"z-meta z-class z-ts\">    <span class=\"z-storage z-modifier z-ts\">private<\/span><span class=\"z-meta z-field z-declaration z-ts\"> <span class=\"z-meta z-definition z-property z-ts\"><span class=\"z-variable z-object z-property z-ts\">iconView<\/span><\/span><span class=\"z-meta z-type z-annotation z-ts\"><span class=\"z-keyword z-operator z-type z-annotation z-ts\">:<\/span> <span class=\"z-entity z-name z-type z-ts\">Picture<\/span> <\/span><span class=\"z-keyword z-operator z-assignment z-ts\">=<\/span> <span class=\"z-new z-expr z-ts\"><span class=\"z-keyword z-operator z-new z-ts\">new<\/span> <span class=\"z-entity z-name z-type z-ts\">Picture<\/span><span class=\"z-meta z-brace z-round z-ts\">(<\/span><span class=\"z-meta z-brace z-round z-ts\">)<\/span><\/span><\/span><span class=\"z-punctuation z-terminator z-statement z-ts\">;<\/span>\n<\/span><\/span><span class=\"z-source z-ts\"><span class=\"z-meta z-class z-ts\">\n<\/span><\/span><span class=\"z-source z-ts\"><span class=\"z-meta z-class z-ts\">    <span class=\"z-meta z-method z-declaration z-ts\"><span class=\"z-storage z-modifier z-ts\">public<\/span> <span class=\"z-meta z-definition z-method z-ts\"><span class=\"z-entity z-name z-function z-ts\">display<\/span><\/span><span class=\"z-meta z-parameters z-ts\"><span class=\"z-punctuation z-definition z-parameters z-begin z-ts\">(<\/span><span class=\"z-punctuation z-definition z-parameters z-end z-ts\">)<\/span><\/span><span class=\"z-meta z-return z-type z-ts\"><span class=\"z-keyword z-operator z-type z-annotation z-ts\">:<\/span> <span class=\"z-support z-type z-primitive z-ts\">void<\/span> <\/span><span class=\"z-meta z-block z-ts\"><span class=\"z-punctuation z-definition z-block z-ts\">{<\/span>\n<\/span><\/span><\/span><\/span><span class=\"z-source z-ts\"><span class=\"z-meta z-class z-ts\"><span class=\"z-meta z-method z-declaration z-ts\"><span class=\"z-meta z-block z-ts\">        <span class=\"z-meta z-function-call z-ts\"><span class=\"z-variable z-language z-this z-ts\">this<\/span><span class=\"z-punctuation z-accessor z-ts\">.<\/span><span class=\"z-variable z-other z-object z-property z-ts\">textView<\/span><span class=\"z-punctuation z-accessor z-ts\">.<\/span><span class=\"z-entity z-name z-function z-ts\">display<\/span><\/span><span class=\"z-meta z-brace z-round z-ts\">(<\/span><span class=\"z-meta z-brace z-round z-ts\">)<\/span><span class=\"z-punctuation z-terminator z-statement z-ts\">;<\/span>\n<\/span><\/span><\/span><\/span><span class=\"z-source z-ts\"><span class=\"z-meta z-class z-ts\"><span class=\"z-meta z-method z-declaration z-ts\"><span class=\"z-meta z-block z-ts\">        <span class=\"z-meta z-function-call z-ts\"><span class=\"z-variable z-language z-this z-ts\">this<\/span><span class=\"z-punctuation z-accessor z-ts\">.<\/span><span class=\"z-variable z-other z-object z-property z-ts\">iconView<\/span><span class=\"z-punctuation z-accessor z-ts\">.<\/span><span class=\"z-entity z-name z-function z-ts\">display<\/span><\/span><span class=\"z-meta z-brace z-round z-ts\">(<\/span><span class=\"z-meta z-brace z-round z-ts\">)<\/span><span class=\"z-punctuation z-terminator z-statement z-ts\">;<\/span>\n<\/span><\/span><\/span><\/span><span class=\"z-source z-ts\"><span class=\"z-meta z-class z-ts\"><span class=\"z-meta z-method z-declaration z-ts\"><span class=\"z-meta z-block z-ts\">    <span class=\"z-punctuation z-definition z-block z-ts\">}<\/span><\/span><\/span>\n<\/span><\/span><span class=\"z-source z-ts\"><span class=\"z-meta z-class z-ts\"><span class=\"z-punctuation z-definition z-block z-ts\">}<\/span><\/span>\n<\/span><\/code><\/pre>\n<h4 id=\"abstractdecorator\">AbstractDecorator<\/h4>\n<p>The base class for all other decorators, it extends the AbstractButton and also has reference to an AbstractButton object.<\/p>\n<pre data-lang=\"ts\" class=\"language-ts z-code\"><code class=\"language-ts\" data-lang=\"ts\"><span class=\"z-source z-ts\"><span class=\"z-meta z-class z-ts\"><span class=\"z-storage z-modifier z-ts\">abstract<\/span> <span class=\"z-storage z-type z-class z-ts\">class<\/span> <span class=\"z-entity z-name z-type z-class z-ts\">ButtonDecorator<\/span> <span class=\"z-storage z-modifier z-ts\">extends<\/span> <span class=\"z-entity z-other z-inherited-class z-ts\">AbstractButton<\/span> <span class=\"z-punctuation z-definition z-block z-ts\">{<\/span>\n<\/span><\/span><span class=\"z-source z-ts\"><span class=\"z-meta z-class z-ts\"><span class=\"z-meta z-method z-declaration z-ts\">    <span class=\"z-storage z-type z-ts\">constructor<\/span><span class=\"z-meta z-parameters z-ts\"><span class=\"z-punctuation z-definition z-parameters z-begin z-ts\">(<\/span><span class=\"z-storage z-modifier z-ts\">protected<\/span> <span class=\"z-variable z-parameter z-ts\">button<\/span><span class=\"z-meta z-type z-annotation z-ts\"><span class=\"z-keyword z-operator z-type z-annotation z-ts\">:<\/span> <span class=\"z-entity z-name z-type z-ts\">AbstractButton<\/span><\/span><span class=\"z-punctuation z-definition z-parameters z-end z-ts\">)<\/span><\/span> <span class=\"z-meta z-block z-ts\"><span class=\"z-punctuation z-definition z-block z-ts\">{<\/span>\n<\/span><\/span><\/span><\/span><span class=\"z-source z-ts\"><span class=\"z-meta z-class z-ts\"><span class=\"z-meta z-method z-declaration z-ts\"><span class=\"z-meta z-block z-ts\">        <span class=\"z-meta z-function-call z-ts\"><span class=\"z-variable z-language z-super z-ts\">super<\/span><\/span><span class=\"z-meta z-brace z-round z-ts\">(<\/span><span class=\"z-meta z-brace z-round z-ts\">)<\/span><span class=\"z-punctuation z-terminator z-statement z-ts\">;<\/span>\n<\/span><\/span><\/span><\/span><span class=\"z-source z-ts\"><span class=\"z-meta z-class z-ts\"><span class=\"z-meta z-method z-declaration z-ts\"><span class=\"z-meta z-block z-ts\">    <span class=\"z-punctuation z-definition z-block z-ts\">}<\/span><\/span><\/span>\n<\/span><\/span><span class=\"z-source z-ts\"><span class=\"z-meta z-class z-ts\">\n<\/span><\/span><span class=\"z-source z-ts\"><span class=\"z-meta z-class z-ts\">    <span class=\"z-meta z-method z-declaration z-ts\"><span class=\"z-storage z-modifier z-ts\">public<\/span> <span class=\"z-meta z-definition z-method z-ts\"><span class=\"z-entity z-name z-function z-ts\">display<\/span><\/span><span class=\"z-meta z-parameters z-ts\"><span class=\"z-punctuation z-definition z-parameters z-begin z-ts\">(<\/span><span class=\"z-punctuation z-definition z-parameters z-end z-ts\">)<\/span><\/span><span class=\"z-meta z-return z-type z-ts\"><span class=\"z-keyword z-operator z-type z-annotation z-ts\">:<\/span> <span class=\"z-support z-type z-primitive z-ts\">void<\/span> <\/span><span class=\"z-meta z-block z-ts\"><span class=\"z-punctuation z-definition z-block z-ts\">{<\/span>\n<\/span><\/span><\/span><\/span><span class=\"z-source z-ts\"><span class=\"z-meta z-class z-ts\"><span class=\"z-meta z-method z-declaration z-ts\"><span class=\"z-meta z-block z-ts\">        <span class=\"z-meta z-function-call z-ts\"><span class=\"z-variable z-language z-this z-ts\">this<\/span><span class=\"z-punctuation z-accessor z-ts\">.<\/span><span class=\"z-variable z-other z-object z-property z-ts\">button<\/span><span class=\"z-punctuation z-accessor z-ts\">.<\/span><span class=\"z-entity z-name z-function z-ts\">display<\/span><\/span><span class=\"z-meta z-brace z-round z-ts\">(<\/span><span class=\"z-meta z-brace z-round z-ts\">)<\/span><span class=\"z-punctuation z-terminator z-statement z-ts\">;<\/span>\n<\/span><\/span><\/span><\/span><span class=\"z-source z-ts\"><span class=\"z-meta z-class z-ts\"><span class=\"z-meta z-method z-declaration z-ts\"><span class=\"z-meta z-block z-ts\">    <span class=\"z-punctuation z-definition z-block z-ts\">}<\/span><\/span><\/span>\n<\/span><\/span><span class=\"z-source z-ts\"><span class=\"z-meta z-class z-ts\"><span class=\"z-punctuation z-definition z-block z-ts\">}<\/span><\/span>\n<\/span><\/code><\/pre>\n<h4 id=\"borderdecorator\">BorderDecorator<\/h4>\n<p>A concrete decorator that extends <code>ButtonDecorator<\/code> and overrides the <code>display<\/code> function to render a border. In this case, border is rendered before button is rendered, but it doesn\u2019t mean it should be always this way.<\/p>\n<pre data-lang=\"ts\" class=\"language-ts z-code\"><code class=\"language-ts\" data-lang=\"ts\"><span class=\"z-source z-ts\"><span class=\"z-meta z-class z-ts\"><span class=\"z-storage z-type z-class z-ts\">class<\/span> <span class=\"z-entity z-name z-type z-class z-ts\">ButtonBorderDecorator<\/span> <span class=\"z-storage z-modifier z-ts\">extends<\/span> <span class=\"z-entity z-other z-inherited-class z-ts\">ButtonDecorator<\/span> <span class=\"z-punctuation z-definition z-block z-ts\">{<\/span>\n<\/span><\/span><span class=\"z-source z-ts\"><span class=\"z-meta z-class z-ts\">    <span class=\"z-storage z-modifier z-ts\">private<\/span><span class=\"z-meta z-field z-declaration z-ts\"> <span class=\"z-meta z-definition z-property z-ts\"><span class=\"z-variable z-object z-property z-ts\">border<\/span><\/span><span class=\"z-meta z-type z-annotation z-ts\"><span class=\"z-keyword z-operator z-type z-annotation z-ts\">:<\/span> <span class=\"z-entity z-name z-type z-ts\">Box<\/span> <\/span><span class=\"z-keyword z-operator z-assignment z-ts\">=<\/span> <span class=\"z-new z-expr z-ts\"><span class=\"z-keyword z-operator z-new z-ts\">new<\/span> <span class=\"z-entity z-name z-type z-ts\">Box<\/span><span class=\"z-meta z-brace z-round z-ts\">(<\/span><span class=\"z-meta z-brace z-round z-ts\">)<\/span><\/span><\/span><span class=\"z-punctuation z-terminator z-statement z-ts\">;<\/span>\n<\/span><\/span><span class=\"z-source z-ts\"><span class=\"z-meta z-class z-ts\">\n<\/span><\/span><span class=\"z-source z-ts\"><span class=\"z-meta z-class z-ts\"><span class=\"z-meta z-method z-declaration z-ts\">    <span class=\"z-meta z-definition z-method z-ts\"><span class=\"z-entity z-name z-function z-ts\">display<\/span><\/span><span class=\"z-meta z-parameters z-ts\"><span class=\"z-punctuation z-definition z-parameters z-begin z-ts\">(<\/span><span class=\"z-punctuation z-definition z-parameters z-end z-ts\">)<\/span><\/span> <span class=\"z-meta z-block z-ts\"><span class=\"z-punctuation z-definition z-block z-ts\">{<\/span>\n<\/span><\/span><\/span><\/span><span class=\"z-source z-ts\"><span class=\"z-meta z-class z-ts\"><span class=\"z-meta z-method z-declaration z-ts\"><span class=\"z-meta z-block z-ts\">        <span class=\"z-meta z-function-call z-ts\"><span class=\"z-variable z-language z-this z-ts\">this<\/span><span class=\"z-punctuation z-accessor z-ts\">.<\/span><span class=\"z-support z-variable z-property z-dom z-ts\">border<\/span><span class=\"z-punctuation z-accessor z-ts\">.<\/span><span class=\"z-entity z-name z-function z-ts\">display<\/span><\/span><span class=\"z-meta z-brace z-round z-ts\">(<\/span><span class=\"z-meta z-brace z-round z-ts\">)<\/span><span class=\"z-punctuation z-terminator z-statement z-ts\">;<\/span>\n<\/span><\/span><\/span><\/span><span class=\"z-source z-ts\"><span class=\"z-meta z-class z-ts\"><span class=\"z-meta z-method z-declaration z-ts\"><span class=\"z-meta z-block z-ts\">        <span class=\"z-meta z-function-call z-ts\"><span class=\"z-variable z-language z-super z-ts\">super<\/span><span class=\"z-punctuation z-accessor z-ts\">.<\/span><span class=\"z-entity z-name z-function z-ts\">display<\/span><\/span><span class=\"z-meta z-brace z-round z-ts\">(<\/span><span class=\"z-meta z-brace z-round z-ts\">)<\/span><span class=\"z-punctuation z-terminator z-statement z-ts\">;<\/span>\n<\/span><\/span><\/span><\/span><span class=\"z-source z-ts\"><span class=\"z-meta z-class z-ts\"><span class=\"z-meta z-method z-declaration z-ts\"><span class=\"z-meta z-block z-ts\">    <span class=\"z-punctuation z-definition z-block z-ts\">}<\/span><\/span><\/span>\n<\/span><\/span><span class=\"z-source z-ts\"><span class=\"z-meta z-class z-ts\"><span class=\"z-punctuation z-definition z-block z-ts\">}<\/span><\/span>\n<\/span><\/code><\/pre>\n<h4 id=\"usageexample\">UsageExample<\/h4>\n<p>You create a push button, then you create a decorator, sending push button in constructor. And in the end you call <code>display<\/code> on the decorator component.<\/p>\n<pre data-lang=\"ts\" class=\"language-ts z-code\"><code class=\"language-ts\" data-lang=\"ts\"><span class=\"z-source z-ts\"><span class=\"z-meta z-var z-expr z-ts\"><span class=\"z-storage z-type z-ts\">let<\/span> <span class=\"z-meta z-var-single-variable z-expr z-ts\"><span class=\"z-meta z-definition z-variable z-ts\"><span class=\"z-variable z-other z-readwrite z-ts\">pushButton<\/span><\/span> <\/span><span class=\"z-keyword z-operator z-assignment z-ts\">=<\/span> <span class=\"z-new z-expr z-ts\"><span class=\"z-keyword z-operator z-new z-ts\">new<\/span> <span class=\"z-entity z-name z-type z-ts\">PushButton<\/span><span class=\"z-meta z-brace z-round z-ts\">(<\/span><span class=\"z-meta z-brace z-round z-ts\">)<\/span><\/span><\/span><span class=\"z-punctuation z-terminator z-statement z-ts\">;<\/span>\n<\/span><span class=\"z-source z-ts\"><span class=\"z-meta z-var z-expr z-ts\"><span class=\"z-storage z-type z-ts\">let<\/span> <span class=\"z-meta z-var-single-variable z-expr z-ts\"><span class=\"z-meta z-definition z-variable z-ts\"><span class=\"z-variable z-other z-readwrite z-ts\">pushButtonWithBorder<\/span><\/span> <\/span><span class=\"z-keyword z-operator z-assignment z-ts\">=<\/span> <span class=\"z-new z-expr z-ts\"><span class=\"z-keyword z-operator z-new z-ts\">new<\/span> <span class=\"z-entity z-name z-type z-ts\">ButtonBorderDecorator<\/span><span class=\"z-meta z-brace z-round z-ts\">(<\/span><span class=\"z-variable z-other z-readwrite z-ts\">pushButton<\/span><span class=\"z-meta z-brace z-round z-ts\">)<\/span><\/span><\/span><span class=\"z-punctuation z-terminator z-statement z-ts\">;<\/span>\n<\/span><span class=\"z-source z-ts\"><span class=\"z-meta z-function-call z-ts\"><span class=\"z-variable z-other z-object z-ts\">pushButtonWithBorder<\/span><span class=\"z-punctuation z-accessor z-ts\">.<\/span><span class=\"z-entity z-name z-function z-ts\">display<\/span><\/span><span class=\"z-meta z-brace z-round z-ts\">(<\/span><span class=\"z-meta z-brace z-round z-ts\">)<\/span><span class=\"z-punctuation z-terminator z-statement z-ts\">;<\/span>\n<\/span><\/code><\/pre>\n<p>The following log should be visible in console<\/p>\n<p><em>press \u2018Run\u2019 button top right, after a new empty window is opened, right-click &gt; inspect element &gt; console<\/em><\/p>\n<pre data-lang=\"sh\" class=\"language-sh z-code\"><code class=\"language-sh\" data-lang=\"sh\"><span class=\"z-source z-shell z-bash\"><span class=\"z-keyword z-operator z-assignment z-redirection z-shell\">&lt;<\/span>Box<span class=\"z-keyword z-operator z-assignment z-redirection z-shell\">&gt;<\/span>\n<\/span><span class=\"z-source z-shell z-bash\"><span class=\"z-keyword z-operator z-assignment z-redirection z-shell\">&lt;<\/span>TextView<span class=\"z-keyword z-operator z-assignment z-redirection z-shell\">&gt;<\/span>\n<\/span><span class=\"z-source z-shell z-bash\"><span class=\"z-keyword z-operator z-assignment z-redirection z-shell\">&lt;<\/span>Picture<span class=\"z-keyword z-operator z-assignment z-redirection z-shell\">&gt;<\/span>\n<\/span><\/code><\/pre>\n<h4 id=\"more-complex-situations\">More complex situations<\/h4>\n<p>This looks like a correct implementation of the decorator pattern, but using this solution, there are some disadvantages when using the button and decorators. When you will need to modify some properties inside button, or in a decorator, you need to keep references to all decorators and buttons. This will make code look pretty bad.<\/p>\n<p>Imagine a more complex example like the following.(<em>It will not compile because <code>BackgroundButtonDecorator<\/code> doesn\u2019t exists, but you can easily create one cloning the <code>BorderButtonDecorator<\/code><\/em>)<\/p>\n<pre data-lang=\"ts\" class=\"language-ts z-code\"><code class=\"language-ts\" data-lang=\"ts\"><span class=\"z-source z-ts\"><span class=\"z-meta z-class z-ts\"><span class=\"z-storage z-type z-class z-ts\">class<\/span> <span class=\"z-entity z-name z-type z-class z-ts\">LoginDialog<\/span> <span class=\"z-punctuation z-definition z-block z-ts\">{<\/span>\n<\/span><\/span><span class=\"z-source z-ts\"><span class=\"z-meta z-class z-ts\"><span class=\"z-meta z-field z-declaration z-ts\">    <span class=\"z-meta z-definition z-property z-ts\"><span class=\"z-variable z-object z-property z-ts\">loginButton<\/span><\/span> <span class=\"z-keyword z-operator z-assignment z-ts\">=<\/span> <span class=\"z-new z-expr z-ts\"><span class=\"z-keyword z-operator z-new z-ts\">new<\/span> <span class=\"z-entity z-name z-type z-ts\">PushButton<\/span><span class=\"z-meta z-brace z-round z-ts\">(<\/span><span class=\"z-meta z-brace z-round z-ts\">)<\/span><\/span><\/span><span class=\"z-punctuation z-terminator z-statement z-ts\">;<\/span>\n<\/span><\/span><span class=\"z-source z-ts\"><span class=\"z-meta z-class z-ts\"><span class=\"z-meta z-field z-declaration z-ts\">    <span class=\"z-meta z-definition z-property z-ts\"><span class=\"z-variable z-object z-property z-ts\">registerButton<\/span><\/span> <span class=\"z-keyword z-operator z-assignment z-ts\">=<\/span> <span class=\"z-new z-expr z-ts\"><span class=\"z-keyword z-operator z-new z-ts\">new<\/span> <span class=\"z-entity z-name z-type z-ts\">PushButton<\/span><span class=\"z-meta z-brace z-round z-ts\">(<\/span><span class=\"z-meta z-brace z-round z-ts\">)<\/span><\/span><\/span><span class=\"z-punctuation z-terminator z-statement z-ts\">;<\/span>\n<\/span><\/span><span class=\"z-source z-ts\"><span class=\"z-meta z-class z-ts\"><span class=\"z-meta z-field z-declaration z-ts\">    <span class=\"z-meta z-definition z-property z-ts\"><span class=\"z-variable z-object z-property z-ts\">forgotPasswordButton<\/span><\/span> <span class=\"z-keyword z-operator z-assignment z-ts\">=<\/span> <span class=\"z-new z-expr z-ts\"><span class=\"z-keyword z-operator z-new z-ts\">new<\/span> <span class=\"z-entity z-name z-type z-ts\">PushButton<\/span><span class=\"z-meta z-brace z-round z-ts\">(<\/span><span class=\"z-meta z-brace z-round z-ts\">)<\/span><\/span><\/span><span class=\"z-punctuation z-terminator z-statement z-ts\">;<\/span>\n<\/span><\/span><span class=\"z-source z-ts\"><span class=\"z-meta z-class z-ts\"><span class=\"z-meta z-field z-declaration z-ts\">    <span class=\"z-meta z-definition z-property z-ts\"><span class=\"z-variable z-object z-property z-ts\">loginBorder<\/span><\/span><span class=\"z-keyword z-operator z-optional z-ts\">?<\/span><span class=\"z-meta z-type z-annotation z-ts\"><span class=\"z-keyword z-operator z-type z-annotation z-ts\">:<\/span> <span class=\"z-entity z-name z-type z-ts\">ButtonBorderDecorator<\/span><\/span><\/span><span class=\"z-punctuation z-terminator z-statement z-ts\">;<\/span>\n<\/span><\/span><span class=\"z-source z-ts\"><span class=\"z-meta z-class z-ts\"><span class=\"z-meta z-field z-declaration z-ts\">    <span class=\"z-meta z-definition z-property z-ts\"><span class=\"z-variable z-object z-property z-ts\">registerBorder<\/span><\/span><span class=\"z-keyword z-operator z-optional z-ts\">?<\/span><span class=\"z-meta z-type z-annotation z-ts\"><span class=\"z-keyword z-operator z-type z-annotation z-ts\">:<\/span> <span class=\"z-entity z-name z-type z-ts\">ButtonBorderDecorator<\/span><\/span><\/span><span class=\"z-punctuation z-terminator z-statement z-ts\">;<\/span>\n<\/span><\/span><span class=\"z-source z-ts\"><span class=\"z-meta z-class z-ts\"><span class=\"z-meta z-field z-declaration z-ts\">    <span class=\"z-meta z-definition z-property z-ts\"><span class=\"z-variable z-object z-property z-ts\">forgotPasswordBackground<\/span><\/span><span class=\"z-keyword z-operator z-optional z-ts\">?<\/span><span class=\"z-meta z-type z-annotation z-ts\"><span class=\"z-keyword z-operator z-type z-annotation z-ts\">:<\/span> <span class=\"z-entity z-name z-type z-ts\">BackgroundButtonDecorator<\/span><\/span><\/span><span class=\"z-punctuation z-terminator z-statement z-ts\">;<\/span>\n<\/span><\/span><span class=\"z-source z-ts\"><span class=\"z-meta z-class z-ts\">\n<\/span><\/span><span class=\"z-source z-ts\"><span class=\"z-meta z-class z-ts\"><span class=\"z-meta z-method z-declaration z-ts\">    <span class=\"z-meta z-definition z-method z-ts\"><span class=\"z-entity z-name z-function z-ts\">render<\/span><\/span><span class=\"z-meta z-parameters z-ts\"><span class=\"z-punctuation z-definition z-parameters z-begin z-ts\">(<\/span><span class=\"z-punctuation z-definition z-parameters z-end z-ts\">)<\/span><\/span><span class=\"z-meta z-return z-type z-ts\"><span class=\"z-keyword z-operator z-type z-annotation z-ts\">:<\/span> <span class=\"z-support z-type z-primitive z-ts\">void<\/span> <\/span><span class=\"z-meta z-block z-ts\"><span class=\"z-punctuation z-definition z-block z-ts\">{<\/span>\n<\/span><\/span><\/span><\/span><span class=\"z-source z-ts\"><span class=\"z-meta z-class z-ts\"><span class=\"z-meta z-method z-declaration z-ts\"><span class=\"z-meta z-block z-ts\">        <span class=\"z-variable z-language z-this z-ts\">this<\/span><span class=\"z-punctuation z-accessor z-ts\">.<\/span><span class=\"z-variable z-other z-property z-ts\">loginBorder<\/span> <span class=\"z-keyword z-operator z-assignment z-ts\">=<\/span> <span class=\"z-new z-expr z-ts\"><span class=\"z-keyword z-operator z-new z-ts\">new<\/span> <span class=\"z-entity z-name z-type z-ts\">ButtonBorderDecorator<\/span><span class=\"z-meta z-brace z-round z-ts\">(<\/span><span class=\"z-variable z-language z-this z-ts\">this<\/span><span class=\"z-punctuation z-accessor z-ts\">.<\/span><span class=\"z-variable z-other z-property z-ts\">loginButton<\/span><span class=\"z-meta z-brace z-round z-ts\">)<\/span><\/span><span class=\"z-punctuation z-terminator z-statement z-ts\">;<\/span>\n<\/span><\/span><\/span><\/span><span class=\"z-source z-ts\"><span class=\"z-meta z-class z-ts\"><span class=\"z-meta z-method z-declaration z-ts\"><span class=\"z-meta z-block z-ts\">        <span class=\"z-variable z-language z-this z-ts\">this<\/span><span class=\"z-punctuation z-accessor z-ts\">.<\/span><span class=\"z-variable z-other z-property z-ts\">registerBorder<\/span> <span class=\"z-keyword z-operator z-assignment z-ts\">=<\/span> <span class=\"z-new z-expr z-ts\"><span class=\"z-keyword z-operator z-new z-ts\">new<\/span> <span class=\"z-entity z-name z-type z-ts\">ButtonBorderDecorator<\/span><span class=\"z-meta z-brace z-round z-ts\">(<\/span><span class=\"z-variable z-language z-this z-ts\">this<\/span><span class=\"z-punctuation z-accessor z-ts\">.<\/span><span class=\"z-variable z-other z-property z-ts\">registerButton<\/span><span class=\"z-meta z-brace z-round z-ts\">)<\/span><\/span><span class=\"z-punctuation z-terminator z-statement z-ts\">;<\/span>\n<\/span><\/span><\/span><\/span><span class=\"z-source z-ts\"><span class=\"z-meta z-class z-ts\"><span class=\"z-meta z-method z-declaration z-ts\"><span class=\"z-meta z-block z-ts\">        <span class=\"z-variable z-language z-this z-ts\">this<\/span><span class=\"z-punctuation z-accessor z-ts\">.<\/span><span class=\"z-variable z-other z-property z-ts\">forgotPasswordBackground<\/span> <span class=\"z-keyword z-operator z-assignment z-ts\">=<\/span> <span class=\"z-new z-expr z-ts\"><span class=\"z-keyword z-operator z-new z-ts\">new<\/span> <span class=\"z-entity z-name z-type z-ts\">BackgroundButtonDecorator<\/span><span class=\"z-meta z-brace z-round z-ts\">(<\/span><span class=\"z-variable z-language z-this z-ts\">this<\/span><span class=\"z-punctuation z-accessor z-ts\">.<\/span><span class=\"z-variable z-other z-property z-ts\">forgotPasswordButton<\/span><span class=\"z-meta z-brace z-round z-ts\">)<\/span><\/span><span class=\"z-punctuation z-terminator z-statement z-ts\">;<\/span>\n<\/span><\/span><\/span><\/span><span class=\"z-source z-ts\"><span class=\"z-meta z-class z-ts\"><span class=\"z-meta z-method z-declaration z-ts\"><span class=\"z-meta z-block z-ts\">        <span class=\"z-meta z-function-call z-ts\"><span class=\"z-variable z-language z-this z-ts\">this<\/span><span class=\"z-punctuation z-accessor z-ts\">.<\/span><span class=\"z-variable z-other z-object z-property z-ts\">loginBorder<\/span><span class=\"z-punctuation z-accessor z-ts\">.<\/span><span class=\"z-entity z-name z-function z-ts\">display<\/span><\/span><span class=\"z-meta z-brace z-round z-ts\">(<\/span><span class=\"z-meta z-brace z-round z-ts\">)<\/span><span class=\"z-punctuation z-terminator z-statement z-ts\">;<\/span>\n<\/span><\/span><\/span><\/span><span class=\"z-source z-ts\"><span class=\"z-meta z-class z-ts\"><span class=\"z-meta z-method z-declaration z-ts\"><span class=\"z-meta z-block z-ts\">        <span class=\"z-meta z-function-call z-ts\"><span class=\"z-variable z-language z-this z-ts\">this<\/span><span class=\"z-punctuation z-accessor z-ts\">.<\/span><span class=\"z-variable z-other z-object z-property z-ts\">registerBorder<\/span><span class=\"z-punctuation z-accessor z-ts\">.<\/span><span class=\"z-entity z-name z-function z-ts\">display<\/span><\/span><span class=\"z-meta z-brace z-round z-ts\">(<\/span><span class=\"z-meta z-brace z-round z-ts\">)<\/span><span class=\"z-punctuation z-terminator z-statement z-ts\">;<\/span>\n<\/span><\/span><\/span><\/span><span class=\"z-source z-ts\"><span class=\"z-meta z-class z-ts\"><span class=\"z-meta z-method z-declaration z-ts\"><span class=\"z-meta z-block z-ts\">        <span class=\"z-meta z-function-call z-ts\"><span class=\"z-variable z-language z-this z-ts\">this<\/span><span class=\"z-punctuation z-accessor z-ts\">.<\/span><span class=\"z-variable z-other z-object z-property z-ts\">forgotPasswordBackground<\/span><span class=\"z-punctuation z-accessor z-ts\">.<\/span><span class=\"z-entity z-name z-function z-ts\">render<\/span><\/span><span class=\"z-meta z-brace z-round z-ts\">(<\/span><span class=\"z-meta z-brace z-round z-ts\">)<\/span><span class=\"z-punctuation z-terminator z-statement z-ts\">;<\/span>\n<\/span><\/span><\/span><\/span><span class=\"z-source z-ts\"><span class=\"z-meta z-class z-ts\"><span class=\"z-meta z-method z-declaration z-ts\"><span class=\"z-meta z-block z-ts\">    <span class=\"z-punctuation z-definition z-block z-ts\">}<\/span><\/span><\/span>\n<\/span><\/span><span class=\"z-source z-ts\"><span class=\"z-meta z-class z-ts\"><span class=\"z-punctuation z-definition z-block z-ts\">}<\/span><\/span>\n<\/span><\/code><\/pre>\n<p>To solve this problem, there should be another class that encapsulates and hides logic of creating buttons with decorators.<\/p>\n<h4 id=\"decoratedbutton\">DecoratedButton<\/h4>\n<p>A facade class that provides a single place to create and control button + decorators. <code>Facade<\/code> is just another OOP pattern<\/p>\n<pre data-lang=\"ts\" class=\"language-ts z-code\"><code class=\"language-ts\" data-lang=\"ts\"><span class=\"z-source z-ts\"><span class=\"z-meta z-interface z-ts\"><span class=\"z-storage z-type z-interface z-ts\">interface<\/span> <span class=\"z-entity z-name z-type z-interface z-ts\">IButtonConstructor<\/span><span class=\"z-meta z-type z-parameters z-ts\"><span class=\"z-punctuation z-definition z-typeparameters z-begin z-ts\">&lt;<\/span><span class=\"z-entity z-name z-type z-ts\">T<\/span><span class=\"z-punctuation z-definition z-typeparameters z-end z-ts\">&gt;<\/span><\/span> <span class=\"z-punctuation z-definition z-block z-ts\">{<\/span>\n<\/span><\/span><span class=\"z-source z-ts\"><span class=\"z-meta z-interface z-ts\"><span class=\"z-meta z-method z-declaration z-ts\">    <span class=\"z-keyword z-operator z-new z-ts\">new<\/span><span class=\"z-meta z-parameters z-ts\"><span class=\"z-punctuation z-definition z-parameters z-begin z-ts\">(<\/span><span class=\"z-punctuation z-definition z-parameters z-end z-ts\">)<\/span><\/span><span class=\"z-meta z-return z-type z-ts\"><span class=\"z-keyword z-operator z-type z-annotation z-ts\">:<\/span> <span class=\"z-entity z-name z-type z-ts\">T<\/span><\/span><\/span><span class=\"z-punctuation z-terminator z-statement z-ts\">;<\/span>\n<\/span><\/span><span class=\"z-source z-ts\"><span class=\"z-meta z-interface z-ts\"><span class=\"z-punctuation z-definition z-block z-ts\">}<\/span><\/span>\n<\/span><span class=\"z-source z-ts\">\n<\/span><span class=\"z-source z-ts\"><span class=\"z-meta z-class z-ts\"><span class=\"z-storage z-type z-class z-ts\">class<\/span> <span class=\"z-entity z-name z-type z-class z-ts\">DecoratedButton<\/span><span class=\"z-meta z-type z-parameters z-ts\"><span class=\"z-punctuation z-definition z-typeparameters z-begin z-ts\">&lt;<\/span><span class=\"z-entity z-name z-type z-ts\">ButtonType<\/span> <span class=\"z-storage z-modifier z-ts\">extends<\/span> <span class=\"z-entity z-name z-type z-ts\">AbstractButton<\/span><span class=\"z-punctuation z-definition z-typeparameters z-end z-ts\">&gt;<\/span><\/span> <span class=\"z-punctuation z-definition z-block z-ts\">{<\/span>\n<\/span><\/span><span class=\"z-source z-ts\"><span class=\"z-meta z-class z-ts\">    <span class=\"z-storage z-modifier z-ts\">private<\/span><span class=\"z-meta z-field z-declaration z-ts\"> <span class=\"z-meta z-definition z-property z-ts\"><span class=\"z-variable z-object z-property z-ts\">button<\/span><\/span><span class=\"z-meta z-type z-annotation z-ts\"><span class=\"z-keyword z-operator z-type z-annotation z-ts\">:<\/span> <span class=\"z-entity z-name z-type z-ts\">ButtonType<\/span><\/span><\/span><span class=\"z-punctuation z-terminator z-statement z-ts\">;<\/span> <span class=\"z-comment z-line z-double-slash z-ts\"><span class=\"z-punctuation z-definition z-comment z-ts\">\/\/<\/span><\/span><span class=\"z-comment z-line z-double-slash z-ts\"> PushButton or SwitchButton<\/span>\n<\/span><\/span><span class=\"z-source z-ts\"><span class=\"z-meta z-class z-ts\">    <span class=\"z-storage z-modifier z-ts\">private<\/span><span class=\"z-meta z-field z-declaration z-ts\"> <span class=\"z-meta z-definition z-property z-ts\"><span class=\"z-variable z-object z-property z-ts\">borderDecorator<\/span><\/span><span class=\"z-keyword z-operator z-optional z-ts\">?<\/span><span class=\"z-meta z-type z-annotation z-ts\"><span class=\"z-keyword z-operator z-type z-annotation z-ts\">:<\/span> <span class=\"z-entity z-name z-type z-ts\">ButtonBorderDecorator<\/span><\/span><\/span><span class=\"z-punctuation z-terminator z-statement z-ts\">;<\/span>\n<\/span><\/span><span class=\"z-source z-ts\"><span class=\"z-meta z-class z-ts\">    <span class=\"z-storage z-modifier z-ts\">private<\/span><span class=\"z-meta z-field z-declaration z-ts\"> <span class=\"z-meta z-definition z-property z-ts\"><span class=\"z-variable z-object z-property z-ts\">backgroundDecorator<\/span><\/span><span class=\"z-keyword z-operator z-optional z-ts\">?<\/span><span class=\"z-meta z-type z-annotation z-ts\"><span class=\"z-keyword z-operator z-type z-annotation z-ts\">:<\/span> <span class=\"z-entity z-name z-type z-ts\">ButtonBackgroundDecorator<\/span><\/span><\/span><span class=\"z-punctuation z-terminator z-statement z-ts\">;<\/span>\n<\/span><\/span><span class=\"z-source z-ts\"><span class=\"z-meta z-class z-ts\">    <span class=\"z-storage z-modifier z-ts\">private<\/span><span class=\"z-meta z-field z-declaration z-ts\"> <span class=\"z-meta z-definition z-property z-ts\"><span class=\"z-variable z-object z-property z-ts\">finalDecoration<\/span><\/span><span class=\"z-meta z-type z-annotation z-ts\"><span class=\"z-keyword z-operator z-type z-annotation z-ts\">:<\/span> <span class=\"z-entity z-name z-type z-ts\">AbstractButton<\/span><\/span><\/span><span class=\"z-punctuation z-terminator z-statement z-ts\">;<\/span>\n<\/span><\/span><span class=\"z-source z-ts\"><span class=\"z-meta z-class z-ts\">\n<\/span><\/span><span class=\"z-source z-ts\"><span class=\"z-meta z-class z-ts\"><span class=\"z-meta z-method z-declaration z-ts\">    <span class=\"z-storage z-type z-ts\">constructor<\/span><span class=\"z-meta z-parameters z-ts\"><span class=\"z-punctuation z-definition z-parameters z-begin z-ts\">(<\/span><span class=\"z-variable z-parameter z-ts\">buttonCtor<\/span><span class=\"z-meta z-type z-annotation z-ts\"><span class=\"z-keyword z-operator z-type z-annotation z-ts\">:<\/span> <span class=\"z-entity z-name z-type z-ts\">IButtonConstructor<\/span><span class=\"z-meta z-type z-parameters z-ts\"><span class=\"z-punctuation z-definition z-typeparameters z-begin z-ts\">&lt;<\/span><\/span><span class=\"z-meta z-type z-parameters z-ts\"><span class=\"z-entity z-name z-type z-ts\">ButtonType<\/span><\/span><span class=\"z-meta z-type z-parameters z-ts\"><span class=\"z-punctuation z-definition z-typeparameters z-end z-ts\">&gt;<\/span><\/span><\/span><span class=\"z-punctuation z-definition z-parameters z-end z-ts\">)<\/span><\/span> <span class=\"z-meta z-block z-ts\"><span class=\"z-punctuation z-definition z-block z-ts\">{<\/span>\n<\/span><\/span><\/span><\/span><span class=\"z-source z-ts\"><span class=\"z-meta z-class z-ts\"><span class=\"z-meta z-method z-declaration z-ts\"><span class=\"z-meta z-block z-ts\">        <span class=\"z-variable z-language z-this z-ts\">this<\/span><span class=\"z-punctuation z-accessor z-ts\">.<\/span><span class=\"z-variable z-other z-property z-ts\">button<\/span> <span class=\"z-keyword z-operator z-assignment z-ts\">=<\/span> <span class=\"z-new z-expr z-ts\"><span class=\"z-keyword z-operator z-new z-ts\">new<\/span> <span class=\"z-entity z-name z-type z-ts\">buttonCtor<\/span><span class=\"z-meta z-brace z-round z-ts\">(<\/span><span class=\"z-meta z-brace z-round z-ts\">)<\/span><\/span><span class=\"z-punctuation z-terminator z-statement z-ts\">;<\/span>\n<\/span><\/span><\/span><\/span><span class=\"z-source z-ts\"><span class=\"z-meta z-class z-ts\"><span class=\"z-meta z-method z-declaration z-ts\"><span class=\"z-meta z-block z-ts\">        <span class=\"z-variable z-language z-this z-ts\">this<\/span><span class=\"z-punctuation z-accessor z-ts\">.<\/span><span class=\"z-variable z-other z-property z-ts\">finalDecoration<\/span> <span class=\"z-keyword z-operator z-assignment z-ts\">=<\/span> <span class=\"z-variable z-language z-this z-ts\">this<\/span><span class=\"z-punctuation z-accessor z-ts\">.<\/span><span class=\"z-variable z-other z-property z-ts\">button<\/span><span class=\"z-punctuation z-terminator z-statement z-ts\">;<\/span>\n<\/span><\/span><\/span><\/span><span class=\"z-source z-ts\"><span class=\"z-meta z-class z-ts\"><span class=\"z-meta z-method z-declaration z-ts\"><span class=\"z-meta z-block z-ts\">    <span class=\"z-punctuation z-definition z-block z-ts\">}<\/span><\/span><\/span>\n<\/span><\/span><span class=\"z-source z-ts\"><span class=\"z-meta z-class z-ts\">\n<\/span><\/span><span class=\"z-source z-ts\"><span class=\"z-meta z-class z-ts\">    <span class=\"z-meta z-method z-declaration z-ts\"><span class=\"z-storage z-modifier z-ts\">public<\/span> <span class=\"z-meta z-definition z-method z-ts\"><span class=\"z-entity z-name z-function z-ts\">addBorderDecorator<\/span><\/span><span class=\"z-meta z-parameters z-ts\"><span class=\"z-punctuation z-definition z-parameters z-begin z-ts\">(<\/span><span class=\"z-punctuation z-definition z-parameters z-end z-ts\">)<\/span><\/span><span class=\"z-meta z-return z-type z-ts\"><span class=\"z-keyword z-operator z-type z-annotation z-ts\">:<\/span> <span class=\"z-support z-type z-primitive z-ts\">void<\/span> <\/span><span class=\"z-meta z-block z-ts\"><span class=\"z-punctuation z-definition z-block z-ts\">{<\/span>\n<\/span><\/span><\/span><\/span><span class=\"z-source z-ts\"><span class=\"z-meta z-class z-ts\"><span class=\"z-meta z-method z-declaration z-ts\"><span class=\"z-meta z-block z-ts\">        <span class=\"z-variable z-language z-this z-ts\">this<\/span><span class=\"z-punctuation z-accessor z-ts\">.<\/span><span class=\"z-variable z-other z-property z-ts\">borderDecorator<\/span> <span class=\"z-keyword z-operator z-assignment z-ts\">=<\/span> <span class=\"z-new z-expr z-ts\"><span class=\"z-keyword z-operator z-new z-ts\">new<\/span> <span class=\"z-entity z-name z-type z-ts\">ButtonBorderDecorator<\/span><span class=\"z-meta z-brace z-round z-ts\">(<\/span><span class=\"z-variable z-language z-this z-ts\">this<\/span><span class=\"z-punctuation z-accessor z-ts\">.<\/span><span class=\"z-variable z-other z-property z-ts\">finalDecoration<\/span><span class=\"z-meta z-brace z-round z-ts\">)<\/span><\/span><span class=\"z-punctuation z-terminator z-statement z-ts\">;<\/span>\n<\/span><\/span><\/span><\/span><span class=\"z-source z-ts\"><span class=\"z-meta z-class z-ts\"><span class=\"z-meta z-method z-declaration z-ts\"><span class=\"z-meta z-block z-ts\">        <span class=\"z-variable z-language z-this z-ts\">this<\/span><span class=\"z-punctuation z-accessor z-ts\">.<\/span><span class=\"z-variable z-other z-property z-ts\">finalDecoration<\/span> <span class=\"z-keyword z-operator z-assignment z-ts\">=<\/span> <span class=\"z-variable z-language z-this z-ts\">this<\/span><span class=\"z-punctuation z-accessor z-ts\">.<\/span><span class=\"z-variable z-other z-property z-ts\">borderDecorator<\/span><span class=\"z-punctuation z-terminator z-statement z-ts\">;<\/span>\n<\/span><\/span><\/span><\/span><span class=\"z-source z-ts\"><span class=\"z-meta z-class z-ts\"><span class=\"z-meta z-method z-declaration z-ts\"><span class=\"z-meta z-block z-ts\">    <span class=\"z-punctuation z-definition z-block z-ts\">}<\/span><\/span><\/span>\n<\/span><\/span><span class=\"z-source z-ts\"><span class=\"z-meta z-class z-ts\">\n<\/span><\/span><span class=\"z-source z-ts\"><span class=\"z-meta z-class z-ts\">    <span class=\"z-meta z-method z-declaration z-ts\"><span class=\"z-storage z-modifier z-ts\">public<\/span> <span class=\"z-meta z-definition z-method z-ts\"><span class=\"z-entity z-name z-function z-ts\">addBackgroundDecorator<\/span><\/span><span class=\"z-meta z-parameters z-ts\"><span class=\"z-punctuation z-definition z-parameters z-begin z-ts\">(<\/span><span class=\"z-punctuation z-definition z-parameters z-end z-ts\">)<\/span><\/span><span class=\"z-meta z-return z-type z-ts\"><span class=\"z-keyword z-operator z-type z-annotation z-ts\">:<\/span> <span class=\"z-support z-type z-primitive z-ts\">void<\/span> <\/span><span class=\"z-meta z-block z-ts\"><span class=\"z-punctuation z-definition z-block z-ts\">{<\/span>\n<\/span><\/span><\/span><\/span><span class=\"z-source z-ts\"><span class=\"z-meta z-class z-ts\"><span class=\"z-meta z-method z-declaration z-ts\"><span class=\"z-meta z-block z-ts\">        <span class=\"z-variable z-language z-this z-ts\">this<\/span><span class=\"z-punctuation z-accessor z-ts\">.<\/span><span class=\"z-variable z-other z-property z-ts\">backgroundDecorator<\/span> <span class=\"z-keyword z-operator z-assignment z-ts\">=<\/span> <span class=\"z-new z-expr z-ts\"><span class=\"z-keyword z-operator z-new z-ts\">new<\/span> <span class=\"z-entity z-name z-type z-ts\">ButtonBackgroundDecorator<\/span><span class=\"z-meta z-brace z-round z-ts\">(<\/span><span class=\"z-variable z-language z-this z-ts\">this<\/span><span class=\"z-punctuation z-accessor z-ts\">.<\/span><span class=\"z-variable z-other z-property z-ts\">finalDecoration<\/span><span class=\"z-meta z-brace z-round z-ts\">)<\/span><\/span><span class=\"z-punctuation z-terminator z-statement z-ts\">;<\/span>\n<\/span><\/span><\/span><\/span><span class=\"z-source z-ts\"><span class=\"z-meta z-class z-ts\"><span class=\"z-meta z-method z-declaration z-ts\"><span class=\"z-meta z-block z-ts\">        <span class=\"z-variable z-language z-this z-ts\">this<\/span><span class=\"z-punctuation z-accessor z-ts\">.<\/span><span class=\"z-variable z-other z-property z-ts\">finalDecoration<\/span> <span class=\"z-keyword z-operator z-assignment z-ts\">=<\/span> <span class=\"z-variable z-language z-this z-ts\">this<\/span><span class=\"z-punctuation z-accessor z-ts\">.<\/span><span class=\"z-variable z-other z-property z-ts\">backgroundDecorator<\/span><span class=\"z-punctuation z-terminator z-statement z-ts\">;<\/span>\n<\/span><\/span><\/span><\/span><span class=\"z-source z-ts\"><span class=\"z-meta z-class z-ts\"><span class=\"z-meta z-method z-declaration z-ts\"><span class=\"z-meta z-block z-ts\">    <span class=\"z-punctuation z-definition z-block z-ts\">}<\/span><\/span><\/span>\n<\/span><\/span><span class=\"z-source z-ts\"><span class=\"z-meta z-class z-ts\">\n<\/span><\/span><span class=\"z-source z-ts\"><span class=\"z-meta z-class z-ts\">    <span class=\"z-meta z-method z-declaration z-ts\"><span class=\"z-storage z-modifier z-ts\">public<\/span> <span class=\"z-meta z-definition z-method z-ts\"><span class=\"z-entity z-name z-function z-ts\">render<\/span><\/span><span class=\"z-meta z-parameters z-ts\"><span class=\"z-punctuation z-definition z-parameters z-begin z-ts\">(<\/span><span class=\"z-punctuation z-definition z-parameters z-end z-ts\">)<\/span><\/span><span class=\"z-meta z-return z-type z-ts\"><span class=\"z-keyword z-operator z-type z-annotation z-ts\">:<\/span> <span class=\"z-support z-type z-primitive z-ts\">void<\/span> <\/span><span class=\"z-meta z-block z-ts\"><span class=\"z-punctuation z-definition z-block z-ts\">{<\/span>\n<\/span><\/span><\/span><\/span><span class=\"z-source z-ts\"><span class=\"z-meta z-class z-ts\"><span class=\"z-meta z-method z-declaration z-ts\"><span class=\"z-meta z-block z-ts\">        <span class=\"z-meta z-function-call z-ts\"><span class=\"z-variable z-language z-this z-ts\">this<\/span><span class=\"z-punctuation z-accessor z-ts\">.<\/span><span class=\"z-variable z-other z-object z-property z-ts\">finalDecoration<\/span><span class=\"z-punctuation z-accessor z-ts\">.<\/span><span class=\"z-entity z-name z-function z-ts\">render<\/span><\/span><span class=\"z-meta z-brace z-round z-ts\">(<\/span><span class=\"z-meta z-brace z-round z-ts\">)<\/span><span class=\"z-punctuation z-terminator z-statement z-ts\">;<\/span>\n<\/span><\/span><\/span><\/span><span class=\"z-source z-ts\"><span class=\"z-meta z-class z-ts\"><span class=\"z-meta z-method z-declaration z-ts\"><span class=\"z-meta z-block z-ts\">    <span class=\"z-punctuation z-definition z-block z-ts\">}<\/span><\/span><\/span>\n<\/span><\/span><span class=\"z-source z-ts\"><span class=\"z-meta z-class z-ts\"><span class=\"z-punctuation z-definition z-block z-ts\">}<\/span><\/span>\n<\/span><\/code><\/pre>\n<p>Now whenever you will need to create a button, the code would look like this. And the result should be same.<\/p>\n<pre data-lang=\"ts\" class=\"language-ts z-code\"><code class=\"language-ts\" data-lang=\"ts\"><span class=\"z-source z-ts\"><span class=\"z-meta z-var z-expr z-ts\"><span class=\"z-storage z-type z-ts\">let<\/span> <span class=\"z-meta z-var-single-variable z-expr z-ts\"><span class=\"z-meta z-definition z-variable z-ts\"><span class=\"z-variable z-other z-readwrite z-ts\">button<\/span><\/span> <\/span><span class=\"z-keyword z-operator z-assignment z-ts\">=<\/span> <span class=\"z-new z-expr z-ts\"><span class=\"z-keyword z-operator z-new z-ts\">new<\/span> <span class=\"z-entity z-name z-type z-ts\">DecoratedButton<\/span><span class=\"z-meta z-brace z-round z-ts\">(<\/span><span class=\"z-variable z-other z-readwrite z-ts\">PushButton<\/span><span class=\"z-meta z-brace z-round z-ts\">)<\/span><\/span><\/span><span class=\"z-punctuation z-terminator z-statement z-ts\">;<\/span>\n<\/span><span class=\"z-source z-ts\"><span class=\"z-meta z-function-call z-ts\"><span class=\"z-variable z-other z-object z-ts\">button<\/span><span class=\"z-punctuation z-accessor z-ts\">.<\/span><span class=\"z-entity z-name z-function z-ts\">addBorderDecorator<\/span><\/span><span class=\"z-meta z-brace z-round z-ts\">(<\/span><span class=\"z-meta z-brace z-round z-ts\">)<\/span><span class=\"z-punctuation z-terminator z-statement z-ts\">;<\/span>\n<\/span><span class=\"z-source z-ts\"><span class=\"z-meta z-function-call z-ts\"><span class=\"z-variable z-other z-object z-ts\">button<\/span><span class=\"z-punctuation z-accessor z-ts\">.<\/span><span class=\"z-entity z-name z-function z-ts\">addBackgroundDecorator<\/span><\/span><span class=\"z-meta z-brace z-round z-ts\">(<\/span><span class=\"z-meta z-brace z-round z-ts\">)<\/span><span class=\"z-punctuation z-terminator z-statement z-ts\">;<\/span>\n<\/span><span class=\"z-source z-ts\"><span class=\"z-meta z-function-call z-ts\"><span class=\"z-variable z-other z-object z-ts\">button<\/span><span class=\"z-punctuation z-accessor z-ts\">.<\/span><span class=\"z-entity z-name z-function z-ts\">render<\/span><\/span><span class=\"z-meta z-brace z-round z-ts\">(<\/span><span class=\"z-meta z-brace z-round z-ts\">)<\/span><span class=\"z-punctuation z-terminator z-statement z-ts\">;<\/span>\n<\/span><\/code><\/pre>\n<h4 id=\"conclusion\">Conclusion<\/h4>\n<p>There are many advantages of using this pattern:<\/p>\n<ul>\n<li>Decorator pattern is a good way to make code follow open-closed principle: code for new decorations, will not be added in any of current classes, but a new class will be created.<\/li>\n<li>Whenever a change will be needed in border, for example adding round border, only one class will be modified, and it will not affect any button class.<\/li>\n<li>When a new button will be created, it will automatically have access to all decorators, and there is no need for inheritance.<\/li>\n<\/ul>\n<p>But also there are some disadvantages:<\/p>\n<ul>\n<li>Too many classes<\/li>\n<li>After an object is decorated, there will be no way to access it from the final decoration. A reference to the original object will be needed.<\/li>\n<\/ul>\n<p>Disadvantages can be hidden inside a <code>facade<\/code> object, and expose a simple interface to the client.<\/p>\n"}]}}