<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Serhiy Butz on Medium]]></title>
        <description><![CDATA[Stories by Serhiy Butz on Medium]]></description>
        <link>https://medium.com/@serhiybutz?source=rss-ed58de3f6add------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*I7iULKVEZELoCcfyKgy-pw.jpeg</url>
            <title>Stories by Serhiy Butz on Medium</title>
            <link>https://medium.com/@serhiybutz?source=rss-ed58de3f6add------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 15:35:10 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@serhiybutz/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[SwiftUI: Spring Animation Completion Tracker]]></title>
            <link>https://serhiybutz.medium.com/swiftui-spring-animation-completion-tracker-fd2a130ff01?source=rss-ed58de3f6add------2</link>
            <guid isPermaLink="false">https://medium.com/p/fd2a130ff01</guid>
            <category><![CDATA[swiftui]]></category>
            <category><![CDATA[completion]]></category>
            <category><![CDATA[spring-animation]]></category>
            <category><![CDATA[animation]]></category>
            <dc:creator><![CDATA[Serhiy Butz]]></dc:creator>
            <pubDate>Thu, 01 Jun 2023 03:46:14 GMT</pubDate>
            <atom:updated>2023-06-01T20:38:38.121Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*t4gD9h0cIkU5lzHpEXfDjQ.jpeg" /></figure><p>I want to share my solution for tracking animation completion in SwiftUI, which effectively handles various types of animations, including spring animations.</p><p>I was inspired by this great article “<a href="https://www.avanderlee.com/swiftui/withanimation-completion-callback/">withAnimation completion callback with animatable modifiers</a>” that suggests the idea of triggering a completion callback by monitoring the animatable parameter and waiting for it to reach the target value. However, for those who strive for perfection (which I occasionally do), this approach may not be entirely satisfying. The reason is that it relies on the assumption that the animation parameter will always be distinct from the target value throughout the animation. This assumption is generally applicable to most commonly used animation curves, except for spring animations.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/893/1*FOZrGH_9k3evaU21s-ZzXA.png" /><figcaption>Picture 1: Demonstration of the problem with spring animations.</figcaption></figure><p>As you can see from the picture above, there’s a probability of the spring animation parameter hitting the target value in one of the oscillations, which means false positives (<em>* The discrete nature of the representation of numerical values makes this not improbable</em>). Even though it’s quite small, and the suggested method can mostly work as an acceptable workaround, for spring animations many people prefer to fallback to manually firing the completion handler after an empirically determined delay.</p><p>My approach is based on a little insight on how animation actually works. Animation is essentially implemented through a smooth transformation of the animation parameter from the original value, to the target value, which is divided into a finite number of moments in time — keyframes. The key aspect of animation lies in the progressive change of the parameter during the animation process, meaning that the animation parameter will always be distinct at two adjacent keyframes. Consequently, we can identify the end of the animation when there is no change between adjacent keyframes! In my experiments, this method has proven effective, but there is a possibility of false positives occurring when, for example, the highest or lowest point of the animation curve falls between adjacent keyframes. To ensure reliability, it is necessary to consider not just two adjacent values but three (as shown in Picture 2)!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/893/1*VvXfRxd_O9JXgcHAran_6A.png" /><figcaption>Picture 2: Demonstration of the idea of tracking 3 adjacent keyframes.</figcaption></figure><p>Here is the code that demonstrates this solution:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JHCn_Kdrx00TudQGpuvXgw.jpeg" /><figcaption><a href="https://gist.github.com/serhiybutz/0e9fde05875a68890a19a2fd7a21a756">Click for gist</a></figcaption></figure><p>And also the convenience code for using this view modifier:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ljcv82GNKIallzygvZozNw.jpeg" /><figcaption><a href="https://gist.github.com/serhiybutz/0e9fde05875a68890a19a2fd7a21a756">Click for gist</a></figcaption></figure><p>In this code, I use a timer for simplicity, with the expectation that it will trigger every keyframe (<em>* Frames typically last 16.7 milliseconds</em>). However, in reality, the timer is not prioritized enough and may be triggered less frequently, especially in the middle of the animation. This makes it even more reasonable to check for 3 contiguous values instead of just 2. After the animation completion, the timer’s triggering rate tends to become more satisfactory, and in my experiments, it accurately determined the end of the animation.</p><p>Ideally, it would be preferable to achieve checking the contiguous animation parameter values at the end of processing <em>each</em> frame. However, this is beyond the scope of this article. If you are interested in an out-of-the-box solution, see this <a href="https://github.com/serhiybutz/AnimationUtils">repository</a> (<em>AnimationStatusReporterModifier.swift</em>).</p><p>To summarize, this universal method is capable of determining the completion of any animation, including spring animations. The main drawback of this approach is that it requires 2 extra frames to determine the state of the animation. This hasn’t really made a difference in my animations so far, but if you have a better idea, I’d be happy to hear about it.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fd2a130ff01" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Swift: Shared memory manager]]></title>
            <link>https://serhiybutz.medium.com/swift-shared-memory-manager-7d96cdf86dc0?source=rss-ed58de3f6add------2</link>
            <guid isPermaLink="false">https://medium.com/p/7d96cdf86dc0</guid>
            <dc:creator><![CDATA[Serhiy Butz]]></dc:creator>
            <pubDate>Tue, 12 Oct 2021 20:59:52 GMT</pubDate>
            <atom:updated>2022-11-02T15:07:44.993Z</atom:updated>
            <content:encoded><![CDATA[<p>Memory allows the computational process to keep track of its state to make progress, so memory working skills are crucial for programmers. But in today&#39;s computing systems, where multiple threads of execution operate simultaneously, the complexity of working with memory takes on a new dimension.</p><p>When a correctly written program is executed in a single thread, its state changes sequentially according to the algorithm, and the result of the computation can be obtained from the state at completion. Even multiple concurrent (operating in parallel) threads, each running sequentially, as long as they do not communicate via shared memory, can safely obtain the desired results. But when different concurrent threads share memory, difficulties arise because the shared memory may be in an intermediate, incoherent state and when that undesirable situation occurs, the program may get the wrong result or even crash. In order to prevent this, we must use <em>thread synchronization</em>, i.e. to ensure that problematic shared memory objects can only be accessed <em>exclusively</em> by one thread at any given time (in fact, this requirement is imposed if at least one thread requires modification access). Thus, the memory state will always be observed by multiple threads in a coherent state.</p><p>In <em>Swift</em>, a commonly recommended way to achieve <em>exclusive mutual memory access</em> is to leverage <a href="https://developer.apple.com/documentation/dispatch/dispatchqueue"><em>Dispatch queues</em></a>, implementing either the <em>EREW</em> (<em>Exclusive Read, Exclusive Write</em>) approach (based on serial queues) or <em>CREW</em> (<em>Concurrent Read, Exclusive Write</em>) approach (based on concurrent queues). Here are <a href="https://github.com/nodes-ios/SwiftSafe/blob/master/Safe/Safe.swift">examples</a> of both.</p><p>Apple&#39;s documentation <a href="https://developer.apple.com/library/archive/documentation/General/Conceptual/ConcurrencyProgrammingGuide/ThreadMigration/ThreadMigration.html#//apple_ref/doc/uid/TP40008091-CH105-SW3">states</a>:</p><blockquote>Replacing your lock-based code with queues <strong>eliminates many of the penalties associated with locks</strong> and also simplifies your remaining code. Instead of using a lock to protect a shared resource, you can instead create a queue to serialize the tasks that access that resource. <strong>Queues do not impose the same penalties as locks.</strong> For example, queueing a task does not require trapping into the kernel to acquire a mutex.</blockquote><p>However, when I benchmarked submitting a task closure to a queue on my macbook (3.1GHz Intel Core i7) I got an overhead of 200<em>ns</em> for a non-capturing task closure and 500<em>ns</em> for a capturing closure. Since today’s <em>lock</em> implementations don’t trap into the kernel for uncontended calls, the overhead of an uncontended lock operation is an order of magnitude lower, e.g., <a href="https://serhiybutz.github.io/swift-mutex-benchmark/">NSLock</a>&#39;s lock/unlock takes approx. 40ns. In most cases, the use of <em>Dispatch queues</em> is justified, but there&#39;re still situations where we want to achieve the best possible performance, and then we have to seek different opportunities with lower-level synchronization primitives, such as NSLock or os_unfair_lock.</p><p>In this post, we will review the traditional state synchronization strategy with <em>lock</em> (aka <em>mutex</em>) and work out a more promising one. We will develop a concurrent construct for more organic synchronization of shared memory accesses. It will be interesting first of all for those who seek to write efficient parallel programs in <em>Swift</em>.</p><h3>Mutexes</h3><p>The intricacy of achieving <em>exclusive mutual memory access</em> by threads is there is no way to achieve this except indirectly, by controlling exclusive access to the <em>program code</em> regions that access shared memory, not memory itself. Such code regions are called <a href="https://en.wikipedia.org/wiki/Critical_section"><em>critical sections</em></a>. The undesirable situation when multiple threads fall into a <em>critical section</em> is called <a href="https://docs.microsoft.com/en-us/archive/msdn-magazine/2005/august/concurrency-what-every-dev-must-know-about-multithreaded-apps#title-2-1_2-2"><em>race conditions</em></a> (or simply <em>races</em>).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*aYQC_VZ1AXUUP_KKfvaWpw.png" /></figure><p>The predominant way to prevent races in a critical section is to protect it with a program object called <a href="https://en.wikipedia.org/wiki/Mutual_exclusion"><em>mutex</em></a> (for <strong>mu</strong>tual <strong>ex</strong>clusion; also known as <em>lock</em>). <em>Mutex</em> provides a pair of methods <em>acquire</em> (alternatively <em>lock</em>) and <em>release</em> (alternatively <em>unlock</em>). Whenever one thread calls <em>acquire</em>, all attempts by other threads to call <em>acquire</em> cause them to wait (go to the sleeping state, or also block) until <em>release</em> is called. The thread that acquired the mutex is <em>owner</em> of the mutex, and it must release the mutex when it is done with the shared memory so that the other threads can access it. Since only one thread can be the owner of a mutex at a time, this assures mutual exclusion.</p><p>Example of usage:</p><pre>mutex.lock()<br>// critical section begins<br>balance -= cost<br>// critical section ends<br>mutex.unlock()</pre><h3>Mutex-to-memory strategy</h3><p>If we abstract away a bit and look at the program state as such, we can think of it as a set of some modelled <em>program properties</em> which are stored in memory (aka <em>memory/concurrent objects</em>; not to be confused with <em>Swift</em> properties). It’s crucial for the program’s correctness that its <em>properties</em> hold true (or be <em>invariant</em>) whenever they are meant to be used.</p><p><em>Properties</em> can be expressed as <em>primitive</em> data types as well as <em>composite</em> data types. Operations on primitive data types can be <em>atomic</em>, and when this is the case, such data types cannot be caught off guard by other threads in an intermediate, incoherent state, and yet, in general, their such intrinsic safety is platform-dependent. Composite data types, on the other hand, are always vulnerable to being seen by other threads in an intermediate state. Therefore, we need to enclose concurrent code regions dealing with <em>any</em> data types in critical sections to make sure that the view of the <em>program properties</em> by other threads is always coherent.</p><p>The predominant basic principle is to <em>methodically</em> associate a particular <em>mutex</em> with a particular <em>program property</em> (a particular region of memory) that it protects. In practice, this means that all <em>critical sections</em> related to a particular <em>property</em> are protected by the <em>property</em>’s own <em>mutex</em>. The <em>methodicality</em> of the association (aka <a href="https://docs.microsoft.com/en-us/archive/msdn-magazine/2005/august/concurrency-what-every-dev-must-know-about-multithreaded-apps">methodical locking</a>) helps to ensure that the mutex-based synchronization is maintained correctly in an extending program. For the sake of simplicity, we will refer to it as <em>mutex-to-memory strategy</em>.</p><p>To make life easier for programmers, some languages (like <em>Java</em> or <em>C#</em>) offer built-in functionality of <em>thread-safe classes</em> (also known as <a href="https://en.wikipedia.org/wiki/Monitor_(synchronization)"><em>monitors</em></a>) to facilitate the synchronization of composite data types, which are essentially just syntactic sugar. For example, <em>Java</em> classes offer a special attribute <em>synchronized</em> for methods, which allows you to easily turn the method body into a <em>critical section</em>. Indeed, why not <a href="https://docs.microsoft.com/en-us/archive/msdn-magazine/2005/august/concurrency-what-every-dev-must-know-about-multithreaded-apps">piggyback on the data abstraction</a> that is already present in an object-oriented design, namely <em>encapsulation</em>, and additionally guarantee synchronized instance state? If <em>program properties</em> are based on <em>thread-safe classes</em>, this guarantees their <em>invariance</em>. Thread-safe classes can be customly implemented in <em>Swift</em> likewise.</p><h3>Is mutex-to-memory strategy optimal?</h3><p>Generally speaking, a program only makes sense when it is capable of progressing through transformations in its state. There either the user triggers a desired operation, or the program algorithm, relying on the <em>program properties</em>, performs certain computations and stepwise updates its state, and eventually the program transforms its state to some coherent, correct form. Basically, any program state transformation can be seen as one or more discrete steps between which the state is correct. Although correctness is always the most important factor when synchronizing shared memory accesses across multiple threads, <em>efficiency</em> should also be considered, because inefficient synchronization can easily cause a program with multiple threads to run slower than the same code executed in a single thread.</p><p>As a simple example, consider the following traffic accounting class that keeps track of the remaining money on the account (in balance) and the traffic consumed (in traffic), which constitute the <em>program properties</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*d728vyyno0jsScQ7qjZcJA.png" /><figcaption><a href="https://gist.github.com/serhiybutz/bffaa0746286020e1191062abd32f869">Click for Gist</a></figcaption></figure><p>Its <em>user interface (hereafter UI) </em>is divided into 2 parts depending on the type of interaction with the state: <a href="https://en.wikipedia.org/wiki/Command%E2%80%93query_separation"><em>queries</em> and <em>commands</em></a>. The <em>queries</em> use <em>read-only</em> access, and in the above example these are the simple currentBalance and currentTraffic computed properties, each with <em>read-only</em> access to one <em>property</em>, and the composite property summary, which has <em>read-only</em> access to both of these <em>properties</em>. The latter is useful for combined reporting. The <em>commands</em> (which are also <a href="https://en.wikipedia.org/wiki/Transaction_processing"><em>transactions</em></a>) use <em>read-write</em> access, and in the above example these are the topUp(for:) and consume(:at:) methods for funding the account and deducting funds for consumed traffic, respectively. The latter, in addition to performing a side effect, also returns the actual amount of consumed traffic from the requested traffic.</p><p>The above code is fine when used in a single-threaded environment, but it’s not at all safe in a multi-threaded environment. So we have to synchronize the accesses:</p><ol><li>all <em>read-write</em> (state-modifying) accesses to the <em>properties</em> must be carefully synchronized</li><li>since there is state modification, the <em>read-only</em> accesses to the <em>properties</em> must also be synchronized.</li></ol><p>The most intuitive way to synchronize access to the <em>properties</em> is to apply <em>mutex-to-memory</em> strategy, i.e., to use a single <em>mutex</em> and simply enclose all the method bodies in lock/unlock calls. And that&#39;s exactly what <em>monitor</em> syntactic sugar would actually do behind the scenes.</p><p>Now let’s take a closer look at the accesses used in the operations. In some of the operations, we only need to access one or the other <em>property</em>, but not both at once, and therefore locking the entire state for each operation is an overkill leading to performance degradation. Each of the state transformations with the <em>mutex-to-memory</em> strategy corresponds to one unified formula:​</p><p>state′ = 𝐹(state)​</p><p>This is a too coarse-grained formula since the semantics of our traffic account entity allows for more fine-grained transformations across the operations with different interdependencies between state chunks (<em>program properties</em>), such as:​</p><p>state.x′ = 𝐹1(state.x)</p><p>state.y′ = 𝐹2(state.y)</p><p>z = 𝐹3(state.x, state.y)​</p><p>Hence, the granularity of synchronization when using the <em>mutex-to-memory</em> strategy leaves much to be desired and we can try to find a better mutual exclusion strategy, other than <em>mutex-to-memory</em>, which allows for better granularity but does not disrupt the program store state logic.</p><h3>Meet mutex-to-operation strategy</h3><p>As seen in the previous section, synchronization based on the association of a particular mutex with a particular memory region is not always optimal. This is because the best strategy lives somewhere in another dimension. We want to dynamically operate on groups of memory objects <em>on a per-operation basis</em>. These memory objects are essentially the source properties and the destination properties of a program that are involved in state mutations. And for the time of a particular state-mutation operation, we want to preserve the <em>properties</em> from access by other parties — put another way, an operation should temporarily <em>own</em> or <em>borrow</em> (conventional terms) the <em>properties</em> for its <em>exclusive</em> use. This will allow us to achieve <a href="https://en.wikipedia.org/wiki/Transaction_processing">transaction processing</a>.</p><p>An abstraction of tracking access to <em>property groups</em>, which we will call <em>Borrowing</em>, becomes apparent. It’s illustrated in the figure below. When an operation is triggered in the thread, a new <em>Borrowing</em> instance with a group of borrowed <em>properties</em> is activated with <em>Shared Manager</em>. <em>Shared Manager</em> only activates the borrowing if that does not pose a shared <em>property</em> use conflict. To do this, <em>Shared Manager</em> checks for conflicts with already active borrowings, and if a conflict is detected, the original thread is blocked (put to sleep) until the blocking borrowing is revoked, after which the original thread is awakened back. The original thread tries to activate its borrowing with <em>Shared Manager</em> again and repeats this until it succeeds. Only then can the operation on the shared properties be safely performed, at the end of which the original thread revokes the operation’s borrowing.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qq8YLs6ZOMbAhwzLQP_EpQ.png" /></figure><p>This is an alternative thread synchronization approach, which we’ll call <em>mutex-to-operation strategy</em>.</p><p>The great advantage of this solution is that it, if implemented reentrantably, has the potential of composability, unlike, for example, <em>monitor</em>. This means that the programmer can build an app in a modular way, relying only on each component’s interface, without looking at its implementation. And internally, the thread safety of each component can rely on its own <em>Shared Manager</em>, which is hidden from the outside world behind the components interface. Different abstraction layers of a concurrent object can use their own <em>Shared Manager</em>.</p><p>Another noticeable advantage of <em>mutex-to-operation strategy</em> is that this solution is extremely scalable in the sense that it allows using a single instance of <em>Shared Manager</em> throughout the application, for example, as a singleton. Leveraging a single instance of <em>Shared Manager</em> breaks the <a href="https://en.wikipedia.org/wiki/Deadlock#Necessary_conditions">circular wait deadlock condition</a> because there’s always one active borrowing owned by an unblocked thread, which eventually revokes its borrowing at the end of the operation and makes way for other threads to proceed.</p><h3>Implementation in Swift</h3><p>We will develop a module that provides <em>Shared Manager</em> for a custom synchronization construct for <em>mutex-to-operation</em> strategy described, and we’ll start off with the <em>UI</em>.</p><p>First, we need to somehow represent the <em>property</em> of the program so that we can refer to it from the code. To this end, we will have a generic class Property, parameterized by the type of property it represents. To note, the value of the property itself is not part of the <em>UI</em> (not directly accessible by the client code). We&#39;ll protect it by the <em>internal</em> access modifier (actually, it&#39;s by default), which makes it inaccessible outside the module.</p><p>Another detail about shared <em>program properties</em> is that <em>Shared Manager</em> needs to distinguish them from each other without any introspection, i.e., they must have the quality of <em>identity</em>. Reference semantics of the class type will ensure this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rhITR9brGnBFdTLa-MI9_A.png" /><figcaption><a href="https://gist.github.com/serhiybutz/3fef97a3a444571cc91bcbb36ffd6a79">Click for Gist</a></figcaption></figure><p>To provide access to <em>program properties</em>, we will have a special accessor to be supplied by <em>Shared Manager</em> for each given <em>property</em> in the <em>access blocks</em> (<a href="#access_block">see below</a>). In fact, it is a wrapper for the <em>program property</em> whose <em>UI</em> is comprised of a single value property, which provides access to the <em>property</em> itself.</p><p>We will use the struct type for accessors because of its value semantics, which gives better opportunities for <a href="https://developer.apple.com/videos/play/wwdc2015/409/">compiler optimization</a> and the advantage of memory access <a href="https://swift.org/blog/swift-5-exclusivity/">exclusivity enforcement</a>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NKCWBuJgXyZRajDg15q_8A.png" /><figcaption><a href="https://gist.github.com/serhiybutz/0aa9a95f3911ef3aa0022ad671f5914a">Click for Gist</a></figcaption></figure><p>As the <em>UI</em> for <em>Shared Manager</em>, we’ll have the concise <a href="https://en.wikipedia.org/wiki/Higher-order_function#Swift">higher-order</a> functions borrow() (see the below code) whose arguments will be the desired <em>program properties</em> followed by a trailing closure of an <em>access block</em>. <em>Access block</em> will be called by the <em>borrow()</em> function either immediately if the <em>properties</em> are not in use, or, otherwise, right after they become available. The <em>access block</em> receives the accessors of the desired properties as arguments, which is the only way to access the values of the <em>properties</em>.</p><p>To be able to use an arbitrary number of desired <em>properties</em>, we will have the borrow() functions defined <em>n</em> times, with the number of <em>property</em> arguments growing from 1 to <em>n</em>, which are wrappers over the internalBorrow() method that performs the actual functionality. The code below illustrates this approach for <em>n</em> = 2. Notice how these wrapper methods forward their call to the internalBorrow() method with the <em>properties</em> passed in an array – in this way we achieve scalability.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KvyG42upqHMLur3Rsa9bMA.png" /><figcaption><a href="https://gist.github.com/serhiybutz/ef9954be6571a9cdeec269a1004188a4">Click for Gist</a></figcaption></figure><p>Now that we’re done with the <em>UI</em> of <em>Shared Manager</em>, let’s get down to implementing its internal logic.</p><p>We’ll start with the <em>Borrowing</em> (<a href="#borrowing">see above</a>) implementation, and below is the code of the Borrowing class. Instances of Borrowing are created on a per-operation basis. The props property contains a list of the borrowed <em>properties</em> and is used in the hasConflictWith method. As mentioned above, the only information Shared Manager uses internally about <em>properties</em> is their <em>identity</em>, which is exactly what the AnyObject type provides, which is used to reference the borrowed <em>properties</em>.</p><p>The lifetime of an instance of Borrowing matches that of the operation, so it&#39;s the appropriate location for a mutex that will block conflicting threads either. As for the mutex itself, we need a bit different behavior – one that allows us to implement thread blocking that can be controlled from an unblocked thread. When an operation in one thread tries to borrow a <em>property</em>, while another operation in another thread owns that <em>property</em>, the former operation should be blocked until the latter finishes owning the conflicting <em>property</em>. The owning thread is responsible for unblocking waiting threads, if any, once the borrowing is complete.</p><p>The described behavior can be implemented using existing <em>OS</em> synchronization constructs — <a href="https://developer.apple.com/documentation/foundation/nscondition">conditions</a>. The code of the Borrowing class below fulfills such blocking. The wait() method contains the blocking part through which the threads enter the sleeping state and wait until the isRevoked flag is set. The unblocking part is in the revoke() method, and this is where the isRevoked flag is set. The isRevoked flag is accompanied by a special synchronization construct – the <a href="https://developer.apple.com/documentation/foundation/nscondition">condition variable</a>. The Borrowing instances have a single-use lifecycle.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dH2Qc1E8SGgiRVZTaV2kAQ.png" /><figcaption><a href="https://gist.github.com/serhiybutz/2fd29ac4319c5f02e70af390b6a73fd6">Click for Gist</a></figcaption></figure><p>The Registry class is used for bookkeeping of all current borrowings and always reflects the current state of <em>Shared Manager</em>. An important aspect of its implementation is that any change in its state also causes a change of its <em>identity</em>, which prevents <a href="https://en.wikipedia.org/wiki/ABA_problem">ABA problem</a> in handling <em>Shared Manager</em> state in a concurrent environment. Therefore, the <em>UI</em> of Registry uses methods such as copyWithAdded() and copyWithRemoved() to assure this.</p><p>The searchForConflictingBorrowingWith() method searches for an active conflicting borrowing for a new one.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZN9DqLodk9IpAEJGfpGxfQ.png" /><figcaption><a href="https://gist.github.com/serhiybutz/1c4323c2bbc5ae754b9bd4c4b5269b59">Click for Gist</a></figcaption></figure><p><em>Shared Manager</em>, implemented in the SharedManager class of the same name (see the below code), is the glue and at the same time the facade for all parties involved. Its <em>UI</em> is a single internalBorrow() method which incorporates all the logic of our synchronization construct and occurs in 3 phases:</p><ol><li>creation and activation of a <em>borrowing</em> (via the helper method activateBorrowingFor()</li><li>execution of the passed <em>access block</em> (via the passed in closure accessBlock)</li><li>and deactivation of the <em>borrowing</em> (via the helper method deactivateBorrowing())</li></ol><p>The method activateBorrowingFor() is quite complex, because it is responsible for maintaining the state of the entire construct (namely the <em>borrowing</em> registry) in a competitive environment. Its main complication is that we can&#39;t lock the registry for the entire time the internalBorrow() method works, because in some code paths, which is when the borrowed <em>property</em> is already owned, the thread should go to sleep, and due to double locking it will end up deadlocked. Therefore, to avoid such a situation, we only temporarily block the access to the <em>registry</em> just to read it into a local variable (lines 14-16) on entry. Then we continue with the <em>registry</em> unblocked, and on exit we block it again (line 23-29) to commit the changes. That said, when exiting, we first check if the <em>registry</em> has been changed by another thread (line 25), and if so, the whole transaction must be repeated from the beginning. Otherwise, the synchronization logic is broken, which leads to race conditions. If the <em>registry</em> has not changed, then we save the new <em>registry</em> and exit the activateBorrowingFor() method. It is very important to have protection against <a href="https://en.wikipedia.org/wiki/ABA_problem">ABA problem</a>, because the newly borrowed <em>properties</em> can coincide with the other ones in the <em>registry</em> swapped by other threads running in parallel. (In terms of <em>linearizability</em>, we have implemented a <em>nonblocking</em> algorithm with line 25 being the <a href="https://en.wikipedia.org/wiki/Linearizability#Linearization_points"><em>linearization point</em></a>)</p><p>Last but not the least, in the defer section in the method internalBorrow() (lines 7-8), in addition to and after deactivating the created <em>borrowing</em>, its revocation is necessarily performed to unblock the waiting threads, if any.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*v33_8BbzU-Q_wRY5EyDuEg.png" /><figcaption><a href="https://gist.github.com/serhiybutz/6bf8eb8036824542ffad9920daa9325b">Click for Gist</a></figcaption></figure><h3>Example of usage</h3><p>Finally, let’s see how we can apply the synchronization construct we developed for the <em>mutex-to-operation</em> strategy in our <a href="#traffic-account-class-example-original">TrafficAccount class example</a> above:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*teXO3QK3IjTWcPayYSHXiQ.png" /><figcaption><a href="https://gist.github.com/serhiybutz/e650dce7010aa0e52e5fc4d99e19ab29">Click for Gist</a></figcaption></figure><p>In fact, the code structure has not changed at all. Now the <em>properties</em> of balance and traffic are wrapped in the Property class (lines 4-5). We added the sharedManager property for the SharedManager instance (line 7). And we put the body of each operation in the access block of Shared Manager&#39;s borrow() method argument, which follows the arguments of the <em>properties</em> used. Notice, how we refer to the <em>property</em> values inside the access block – they translate into closure&#39;s arguments as accessors (Accessor struct instances), and we always use the value property of the accessor.</p><h3>Conclusion</h3><p>In this article, we saw that working with memory in multi-threaded programs is hard and that access to shared memory needs to be synchronized. Next, we saw that <em>mutex</em> is a universal synchronization mechanism, and we reviewed the predominant methodology for working with <em>mutexes</em>, which is to associate a particular <em>mutex</em> with a particular memory region(s). We referred to it as <em>mutex-to-memory strategy</em>. Next, using the example of a traffic accounting class, we saw how this methodology can be unoptimal and further we discussed how we can do better with an approach of associating a specific <em>mutex</em> with a specific operation, which we named <em>mutex-to-operation strategy</em>. Next, we developed a custom synchronization construct for <em>mutex-to-operation strategy</em> and applied it to our original traffic accounting example.</p><p>In fact, there is still room for improvement in our synchronization construct, such as more optimal handling of the properties of a program by separating accesses by their type: read-only or read-write, but this is not covered in this post. If you are interested in the finished implementation, it is available in this <a href="https://github.com/serhiybutz/Mitra/releases/tag/0.1.0">repository</a>.</p><p>Thank you for reading 🎈</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7d96cdf86dc0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Swift: Mutex benchmark]]></title>
            <link>https://serhiybutz.medium.com/swift-mutex-benchmark-b21ee293d9ad?source=rss-ed58de3f6add------2</link>
            <guid isPermaLink="false">https://medium.com/p/b21ee293d9ad</guid>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[mutex]]></category>
            <category><![CDATA[concurrency]]></category>
            <category><![CDATA[locks]]></category>
            <category><![CDATA[performance]]></category>
            <dc:creator><![CDATA[Serhiy Butz]]></dc:creator>
            <pubDate>Sun, 12 Sep 2021 20:36:12 GMT</pubDate>
            <atom:updated>2022-11-02T15:11:00.883Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*yCHLkwIJNBM5ZxbZ.png" /></figure><p>When designing <em>concurrent</em> programs, correctness is always the most important factor, but you should also consider <em>performance</em> factors as well. Code that executes correctly under multiple threads, but slower than the same code running on a single thread, is hardly an improvement. In this post, I <em>benchmark</em> the overhead of the acquisition/release time of different mutexes available on the <em>Apple</em> platform. The results of this benchmark may be useful when you find yourself faced with choosing the right synchronization primitive.</p><h3>Intro</h3><p>It is unlikely that a developer writing <em>concurrent</em> (<em>multithreaded</em>) code has not dealt with <em>mutexes</em> (or <em>locks</em>), which are the optimal tool for synchronizing multiple threads. To refresh the memory, in a multithreaded, program access to a shared resource is organized through a limited region of code, also known as a <em>critical section</em> and a <em>mutex</em> is a program object that prevents simultaneous access to that region of code, i.e., guarantees <strong>mut</strong>ual <strong>ex</strong>clusion.</p><p><a href="http://alumni.cs.ucr.edu/~kishore/papers/semaphores.pdf">The Little Book of Semaphores</a> gives a mutex metaphor: it is a token that is passed from one thread to another. In an alternative metaphor there, we think of the critical section as a room, and only one thread is allowed to be in the room at a time. In this metaphor, mutexes are called <em>locks</em>, and a thread is said to <em>lock</em> the mutex before entering and <em>unlock</em> it while exiting. The thread that <em>acquires</em> (<em>locks</em>) the mutex is the <em>owner</em> of the mutex. Only after it <em>releases</em> (<em>unlocks</em>) the mutex, another thread can <em>acquire</em> the mutex and become the <em>owner</em>.</p><p>An ordinary mutex will <em>deadlock</em> if the thread-owner tries to lock the mutex again without first unlocking it. But a <a href="https://en.wikipedia.org/wiki/Reentrant*mutex"><em>recursive mutex</em></a> can be locked <em>multiple</em> times by a single thread.</p><h3>Mutex overview</h3><p>On the <em>Apple</em> platform, a bunch of mutexes is available:</p><ul><li><a href="https://developer.apple.com/documentation/os/1646466-os_unfair_lock_lock">os_unfair_lock</a>: a low-level effective lock, which is the replacement for the deprecated OSSpinLock, but instead of spinning on contention, it yields (i.e. it waits in the kernel to be woken up by an unlock). Its state currently fits in a <em>32-bit</em> integer, and the thread ownership information it comprises allows the system to <a href="https://developer.apple.com/documentation/os/1646466-os_unfair_lock_lock">resist</a> priority inversions. As the name suggests it is unfair, meaning, a thread-unlocker can potentially immediately reacquire the lock before a woken up waiting thread gets an opportunity to attempt to acquire the lock. This is advantageous for performance reasons, but also makes starvation of waiting threads a possibility.<br>(There also exists a <em>recursive</em> version, os_unfair_recursive_lock, but it’s currently in a private API).</li><li><a href="https://elias.rhi.hi.is/libc/Mutexes.html">pthread_mutex_t</a>: a comprehensive <em>POSIX Threads</em> (<em>Pthreads</em>) mutex, which is provided by the lower-level C API. The size of its state structure is considerably larger than that of os_unfair_lock, <em>64 bytes</em>. By default it is configured <a href="https://2net.co.uk/tutorial/mutex_mutandis">for <em>maximum speed</em> at the expense of correctness</a>: not only is there no check of the <em>owner</em> and can any thread unlock it (as if it were a <em>binary semaphore</em>). No attempt of <em>priority inversion</em> resolution and <em>fairness</em> control is done either. But it can be configured to respect <em>fairness</em> and perform error checking and <em>priority inheritance</em> if you prefer correctness over speed. A <em>Pthreads</em> mutex can also be configured for <em>recursion</em>. Finally, <em>Pthreads</em> mutex does support <em>condition variables</em>, that, among other things, allows you to establish a <em>wait timeout period</em>.<br>In the benchmark, pthread_mutex_t comes as PthreadMutex.</li><li>pthread_rwlock_t: a <em>Pthreads</em> implementation of a <em>read-write lock</em>. A <em>read-write lock</em> is an advanced mutex that allows concurrent access for read-only operations, while write operations require exclusive access, which is efficient in many scenarios. It has different operations for <em>read locking</em> and for <em>write locking</em>. The size ofpthread_rwlock_t state structure is as much as <em>200 bytes</em>.<br>In the benchmark, pthread_rwlock_t comes as PthreadRWLock_WriteLock and PthreadRWLock_ReadLock for <em>read</em> and <em>write locking</em> respectively.</li><li><a href="https://developer.apple.com/documentation/foundation/nslock/">NSLock</a>: a <em>Foundation</em>-provided <em>Objective-C</em> class for the most general-purpose mutex. Along with it come the classes <a href="https://developer.apple.com/documentation/foundation/nsrecursivelock">NSRecursiveLock</a>, <a href="https://developer.apple.com/documentation/foundation/nsconditionlock">NSConditionLock</a>, <a href="https://developer.apple.com/documentation/foundation/nscondition">NSCondition</a>, <a href="https://developer.apple.com/documentation/foundation/nsdistributedlock">NSDistributedLock</a>, each targeting its own set of problems. Essentially, they all are abstractions based on <em>Pthreads</em> mutex (on <em>macOS</em>/<em>iOS</em>) and therefore do nothing that cannot be done with <em>Pthreads</em> mutex but are easier to use.<br><em>Foundation</em> mutexes use the default (speed-oriented) <em>Pthreads</em> mutex configuration, but they are still somewhat slow. One reason they are slower than the non-<em>Objective-C</em> alternatives is the extra cost of having to go through <em>Objective-C</em> messaging system. Another reason is that they use a combination of synchronization primitives, for example, they have to internally handle a <em>condition variable</em> to support functionality such as <em>wait timeouts</em>, which results in some overhead even when <em>wait timeouts</em> are not used.</li><li>The DispatchSemaphore based <a href="https://www.geeksforgeeks.org/semaphores-in-process-synchronization/">binary semaphore</a>: although it is not a full-fledged mutex (because it <a href="https://blog.feabhas.com/2009/09/mutex-vs-semaphores-%E2%80%93-part-2-the-mutex/">doesn’t allow for ownership</a>) it still could be useful in <a href="https://stackoverflow.com/questions/11528041/where-to-use-binary-semaphore-when-mutex-are-available#answer-11528296">some cases</a> and it looks promising in terms of performance:</li></ul><blockquote>A dispatch semaphore is an efficient implementation of a traditional counting semaphore. Dispatch semaphores call down to the kernel only when the calling thread needs to be blocked. If the calling semaphore does not need to block, no kernel call is made. <a href="https://developer.apple.com/documentation/dispatch/dispatchsemaphore">Read more</a></blockquote><p>The binary semaphore usage:</p><pre><strong>let</strong> biSema <strong>=</strong> <strong>DispatchSemaphore</strong>(value: 1)<br>biSema<strong>.wait</strong>() <em>// lock</em><br><em>// critical section</em><br>biSema<strong>.signal</strong>() <em>// unlock</em></pre><p>In the benchmark, it comes as BiSemaphore.</p><h3>Mutex overhead</h3><p>Mutexes are indispensable when it comes to <em>multithreaded synchronization</em>, but they also have overhead. Basically, any form of synchronization comes with a performance hit.</p><p>Major sources of mutex overhead are:</p><ul><li>the range of functionality provided by mutex implementation, such as <em>recursion</em>, <em>death detection</em>, <em>priority inheritance</em>, <em>wait timeouts</em>, control of thread <em>ownership</em>, etc (<a href="https://blog.feabhas.com/2009/09/mutex-vs-semaphores-%E2%80%93-part-2-the-mutex/">read more</a>)</li><li>need to enter the <em>kernel</em> (read more: <a href="https://stackoverflow.com/questions/39184037/lightweight-mutex#answer-39192864">1</a>, <a href="https://developer.apple.com/library/archive/documentation/Cocoa/Conceptual/Multithreading/ThreadSafety/ThreadSafety.html#//apple*ref/doc/uid/10000057i-CH8-SW10">2</a>)</li><li><em>Objective-C</em> messaging (objc_msgSend calls) on the <em>Apple</em> platform (<a href="https://www.mulle-kybernetik.com/artikel/Optimization/opti-3.html">read more</a>)</li><li>hardware-related causes (<a href="https://docs.microsoft.com/en-us/archive/msdn-magazine/2005/october/understanding-low-lock-techniques-in-multithreaded-apps">read more</a>)</li></ul><p>Mutex <em>overhead</em> is the subject of interest of this benchmark. It can vary depending on what functionality the mutex has to use. For example, in the case of an <em>uncontended</em> call made from single process threads, the mutex may behave as a <a href="https://stackoverflow.com/questions/39184037/lightweight-mutex#answer-39192864">lightweight mutex</a> and not to enter the <em>kernel</em>. Otherwise, a <em>kernel-mode</em> transition and a <em>wait list</em> enqueuing will be involved. Performance may also be affected by the need to handle <em>fairness</em> and prioritize threads. Being able to determine that a single thread is running allows the control flow to switch to a trivial code path.</p><p>Analyzing how mutexes behave under different circumstances and what overheads arise is valuable for concurrent software developers, as the knowledge gained will help improve software quality.</p><h3>Benchmark</h3><p>In this <a href="https://github.com/serhiybutz/MutexBenchmark/blob/master/MutexBenchmark/main.swift">benchmark</a>, I compare the performance of mutexes in the absence of <em>contention</em> with a single thread is running. To get the cleanest possible results, the benchmark was performed from a command line tool application with the <em>Release</em> build configuration (for maximum optimization) and with the <em>Exclusive Access to Memory</em> runtime check disabled.</p><p>The following chart shows the benchmark results I got on a 3.1GHz Dual-Core Intel Core i7 with 16GM of RAM running macOS Catalina v10.15.3, deployment target 10.15. Time is given in <strong>nano</strong>seconds.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*e6aexkX1RRC-UKxRzfRQzg.png" /></figure><p>The <em>Pthreads</em> read-write lock (for both read and write locking) is a bit slower in the diagram. In principle, this is expected because of the complexity of its tasks.</p><p>The performance of the ordinary <em>Foundation</em> lock, NSLock, virtually matches that of the recursive <em>Pthreads</em> mutex, PthreadRecursiveMutex, but its recursive companion NSRecursiveLock is the slowest. In general recursive versions are somewhat slower than their basic versions.</p><p>I have noticed that some items, such as the top two, sometimes tend to change their relative position from time to time. I assume that since these measurements are conducted at the limit of the processor’s capability, side factors such as interrupts have a noticeable effect on the measurement results. Therefore, in order not to speculate, absolute values in the benchmark should be taken in moderation.</p><h3>Summary</h3><p>To summarize, I find that the top three items can be thought of as equivalent in performance and overall the performance of all mutexes in the absence of contention is quite high.</p><p>I also benchmarked pairs of <em>contended</em> calls to the mutexes, and the overhead turned out to be 2 orders of magnitude higher! And for a relatively small number of measurements, it even jumped up to 3 orders of magnitude! Since the arrangement of items in the benchmark varied quite chaotically from time to time, I decided not to present a diagram for them. If you are curious, you can download my <a href="https://github.com/serhiybutz/MutexBenchmark">benchmark project</a> and play with it yourself. Still, some items behaved steadily as opposed to the others, like the BiSemaphore and OSUnfairLock: the measurements (the total time of the <em>lock</em> operation immediately followed by the <em>unlock</em> operation) for them mostly varied in the range of <em>8-10 </em><strong><em>micro</em></strong><em>seconds</em>. Such a drastic degradation in performance is caused by the need for a thread to enter the kernel, go to the sleeping state, and the subsequent awakening.</p><p>You can find the benchmark Xcode project in this <a href="https://github.com/serhiybutz/MutexBenchmark">repository</a>.</p><p>Thanks for reading 🎈</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b21ee293d9ad" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Combine: WithLatestFrom operator]]></title>
            <link>https://serhiybutz.medium.com/combine-withlatestfrom-operator-8c529e809fd3?source=rss-ed58de3f6add------2</link>
            <guid isPermaLink="false">https://medium.com/p/8c529e809fd3</guid>
            <category><![CDATA[reactive-programming]]></category>
            <category><![CDATA[withlatestfrom]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[ios-app-development]]></category>
            <category><![CDATA[combine]]></category>
            <dc:creator><![CDATA[Serhiy Butz]]></dc:creator>
            <pubDate>Sat, 22 Aug 2020 05:52:01 GMT</pubDate>
            <atom:updated>2022-11-02T15:18:03.593Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*kFEgxEif3849Qo8l.jpg" /></figure><p>Despite Apple’s promoting their new <a href="https://developer.apple.com/documentation/SwiftUI">SwiftUI</a> framework, there’re a lot of projects, based on the plain old UIKit framework. Nevertheless, even if this is the case, and you’re tied to UIKit, there’s nothing that gets in the way of adopting <a href="https://developer.apple.com/documentation/Combine">Combine</a>.</p><p>To leverage Combine <a href="https://www.apeth.com/UnderstandingCombine/start/startpipelines.html">pipelines</a> with UIKit, the used UIKit controls have to be integrated with Combine. In general, once that’s done, further work just boils down to establishing <em>pipelines</em> transforming streams of control events and input values.</p><p>In this post, we’ll walk through how in the <a href="https://en.wikipedia.org/wiki/Reactive_programming">RP</a> paradigm with Combine we can implement one practical case: presenting content with the UIKit table view and using a search bar for filtering. Moreover, we’ll prefer a dynamic behavior for the search: as the text in the search field changes, the search results in the table view get automatically updated.</p><p>Notice, we’re going to focus only on important details. If you wish to check out the completed app demonstrating a discussed material, download its Xcode project from <a href="https://github.com/serhiybutz/blog-samples/tree/master/XCombineDemo-WithLatestFrom">here</a>.</p><h3>Search Bar integration</h3><p>We’re going to use <a href="https://developer.apple.com/documentation/uikit/UISearchBar">UISearchBar</a> as a filtering control; let’s start with integrating it with Combine.</p><p>UISearchBar provides a text field for entering text that is vended in the property searchTextField of type <a href="https://developer.apple.com/documentation/uikit/UISearchTextField">UISearchTextField</a>. The UISearchTextField subclasses <a href="https://developer.apple.com/documentation/uikit/UITextField">UITextField</a> which is a good candidate for attaching a publisher of text changes. We can integrate UISearchBar with Combine as shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*-o556918_Sqn12It.png" /><figcaption><a href="https://gist.github.com/serhiybutz/11efb99227bb166e755e3e3c7d02f404">Click for Gist</a></figcaption></figure><p>In the above code, we’re extending UITextField type to retroactively add a publisher of text changes, the property textPublisher of erased type AnyPublisher&lt;String?, Never&gt;. It’s backed by the NotificationCenter publisher, on the default center, which is set up to emit the .textDidChangeNotification notifications produced by the underlying text field instance (<em>lines 7-9</em>). Next in the pipeline, we’re picking Notification’s object field (<em>line 10</em>), downcasting it back to UITextField (<em>line 11</em>), picking its text field (<em>line 12</em>), and erasing the publisher type (<em>line 13</em>).</p><h3>Building pipelines</h3><p>Now that UITextField text publisher has been set up, we can go ahead and establish the search requests processing pipelines, as shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*wFbG4BEx_ZgOvrKk.png" /><figcaption><a href="https://gist.github.com/serhiybutz/245449fdc8386a483c1575718829855e">Click for Gist</a></figcaption></figure><p>We start by defining the searchStream pipeline (<em>line 53-55</em>). To refer to the search bar’s text publisher we’re writing searchBar.searchTextField.textPublisher and then setting up prepending the produced stream with the current value from searchBar.text! (<em>line 54</em>) to get the search results generated initially. Thus, the user’s every single tap on the keyboard will trigger search results generation. But can you see any potential pitfalls here? The problem is that if the user is tapping fast enough and the search runs for every single tap, it can lead to a system overload. To avoid it, we limit the frequency of search requests by extending the previous pipeline with the <a href="https://developer.apple.com/documentation/combine/publisher/debounce(for:scheduler:options:)">debounce</a> operator which will only emit the freshest received value upon an “undisturbed” delay of 0.3s (<em>line 58</em>).</p><p>Finally, our pipeline is terminating by the search results generation method subscribing to it (<em>lines 62–65</em>). Of course, we’re storing the returned subscriber in the view controller’s lifecycle bound storage, cancellables, (<em>line 66</em>) so as it won’t immediately go out of existence.</p><h3>Refresh Control integration</h3><p>To make things even more interesting we’ll want to display the search results in a table view, which uses the <a href="https://developer.apple.com/documentation/uikit/uirefreshcontrol">UIRefreshControl</a> for updating its contents. It means, that when the user pulls the top of the table view’s contents area downward, a search results regeneration will be triggered to update the table view’s contents area.</p><p>First, as with UISearchBar we’ll have to integrate UIRefreshControl with Combine as shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*sPKko30xt-phSOgg.png" /><figcaption><a href="https://gist.github.com/serhiybutz/782b6d3b6a92b1848b3d90d0f1faf0a2">Click for Gist</a></figcaption></figure><p>In the code above, we continue to use Swift extensions to retroactively add a publisher of the refresh beginning events to UIRefreshControl. However, in contrast to UISearchBar, this time we’re unable to take advantage of NotificationCenter publisher because there are no notifications sent for UIRefreshControl’s refresh beginning events. And so we’re setting up our own events publishing, backed by a PassthroughSubject publisher (<em>line 7</em>).</p><p>The major complication has been here that as yet Swift doesn’t support stored instance properties in extensions, and, as a workaround, we’ve used Apple SDK’s associated objects facility. Via the computed property beginRefreshingPublisher (<em>line 45</em>), backed by internalBeginRefreshingPublisher (<em>line 9</em>), we’re both instantiating and accessing the publisher’s associated object that is created only once for a UIRefreshControl instance.</p><p>From the instantiate(_:) method we’re registering the target-action handler handleValueChanged() to listen for .valueChanged events of UIRefreshControl indicating the refresh beginning (<em>line 35</em>). It’s from handleValueChanged() that beginRefreshingPublisher is signalling about the refresh beginning (<em>line 42</em>). That’s it.</p><h3>Introducing withLatestFrom operator</h3><p>Now, that our used UIKit source event controls are integrated with Combine we’re ready to proceed with refreshing the search results upon UIRefreshControl’s signals. Of course, we’re looking for an elegant solution. The clearest one that comes to mind would be based on the withLatestFromoperator, which should be familiar to those with a reactive programming background. The marble diagram of the withLatestFrom operator is shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/755/0*y_qwu-m0HEFf5nHW.png" /></figure><p>If we consider data streams from the perspective of their nature, in essence, they are sequences of elements in time, and their elements are fully determined by two characteristics: value and time. The withLatestFrom operator combines two upstreams by just using one characteristic from elements of one upstream and the opposite from elements of the other. In the record a.withLatestFrom(b), it means that this operator emits a current latest value from the b upstream at times of the aupstream’s elements. However, as yet this operator is missing from the Combine framework.</p><p>So go ahead and introduce our own implementation of the withLatestFrom operator, as shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*BDt8b-zbmsqhHj-t.png" /><figcaption><a href="https://gist.github.com/serhiybutz/59d1c674c53f8a23d2ac773490410940">Click for Gist</a></figcaption></figure><p>The above is the code of a fully-fledged operator. The withLatestFrom operator returns a “<a href="https://medium.com/@benlesh/hot-vs-cold-observables-f8094ed53339">cold</a>” publisher, meaning it creates a new identity for each new downstream subscriber. Let’s step through the above code:</p><ol><li>The class of withLatestFrom operator, WithLatestFrom, (<em>lines 4-33</em>) sits under the Publishers namespace.</li><li>Its initializer takes two upstream publishers as the parameters upstream and other, which are preserved in private properties for future use (<em>lines 20-21</em>).</li><li>Upon subscription, in receive(subscriber:) (<em>line 29</em>), the operator establishes a new inner pipeline responsible for the operator logic.</li><li>The operator logic inner pipeline splits into two sub-pipelines mergedStream and resultsStream which join into one in receive(subscriber:) (<em>lines 29-31</em>).</li><li>One sub-pipeline mergedStream (<em>lines 51-61</em>) is responsible for combining upstream elements of two different types into one stream with elements of an algebraic sum type, the enum MergedElement, and delivering them in an interleaved sequence of elements.</li><li>The other sub-pipeline resultsStream (<em>lines 63-93</em>) uses the stateful operator scan <em>(line 68)</em>to transform the merged element sequence into another producing tuples of the running latest elements of both upstreams <em>(lines 85-86)</em> and the flag shouldEmit <em>(line 87)</em> indicating whether the element should not be filtered out. Then it performs filtering <em>(line 90)</em> and producing the operator’s expected output <em>(line 91)</em>.</li><li>The withLatestFrom operator method is retroactively added to the Publisher type so as it was capable of building up Combine pipelines (<em>lines 97-101</em>).</li></ol><p>Overall, our withLatestFrom operator is fully functional, especially for our purpose. Still, its completion logic remains subject to correction, which is out of the scope here. Check out the corrected implementation of our withLatestFrom operator in the <a href="https://github.com/serhiybutz/XCombine">XCombine repository</a>.</p><h3>Leveraging withLatestFrom operator</h3><p>Time to update our pipelines. In the following code, we’ve incorporated the withLatestFromoperator-based logic for a search results regeneration upon refresh control events.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*mumhzmuOqc5kMqof.png" /><figcaption><a href="https://gist.github.com/serhiybutz/1bf5f9a24675a09e012ce3f0c22018cc">Click for Gist</a></figcaption></figure><p>Let’s step through what’s changed:</p><ol><li>We’re defining the beginRefreshingStream pipeline (<em>lines 10-15</em>) whose purpose is to provide a stream of refresh beginning events. To refer to the refresh control publisher we’re writing refreshControl.beginRefreshingPublisher (<em>lines 10-11</em>).</li><li>Next, we’re piping the stream into the withLatestFrom operator to be a control events source for the provision the operator with times at which it should read the latest values from searchStream (<em>line 12</em>).</li><li>The withLatestFrom operator produces tuples of its both upstreams’ elements combined. We’re reducing withLatestFrom’s produced tuples to mere searchStream elements (<em>line 13</em>).</li><li>Upon the user pulling the refresh control downwards, we allow a visual indication of search regenaration to last for a while (0.3s) by using the <a href="https://developer.apple.com/documentation/combine/publisher/delay(for:tolerance:scheduler:options:)">delay</a> operator (<em>line 14</em>). It has the effect of delaying all pipeline events by 0.3s (which are delivered on the main thread).</li><li>We make two subscriptions to the beginRefreshingStream pipeline. The first one is to finish the refresh control’s visual indication (<em>line 21</em>).</li><li>The second subscription is made by the merge operator to join the two search event streams, sparsedSearchStream and beginRefreshingStream, into one (<em>line 26</em>).</li><li>Finally, the pipeline of joined search events is terminating by the search results generation method subscribing to it (<em>lines 30–33</em>).</li></ol><h3>Wrap up</h3><p>In this blog post we’ve walked through the process of adopting Combine in a UIKit-based app. We integrated two UIKit controls, UISearchBar and UIRefreshControl, with Combine and defined reactive stream pipelines to establish the necessary logic. Apart from that, we developed our own withLatestFrom operator which is absent from Combine yet.</p><p>The completed app demonstrating a discussed material is available as Xcode project <a href="https://github.com/serhiybutz/blog-samples/tree/master/XCombineDemo-WithLatestFrom">here</a>.</p><p>Thanks for reading 🎈</p><p><em>Originally published at </em><a href="https://serhiybutz.github.io/"><em>https://serhiybutz.github.io</em></a><em> on March 21, 2020.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8c529e809fd3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Combine: ShareReplay operator]]></title>
            <link>https://serhiybutz.medium.com/combine-sharereplay-operator-634f2516579?source=rss-ed58de3f6add------2</link>
            <guid isPermaLink="false">https://medium.com/p/634f2516579</guid>
            <category><![CDATA[reactive-programming]]></category>
            <category><![CDATA[combine]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[ios-app-development]]></category>
            <category><![CDATA[sharereplay]]></category>
            <dc:creator><![CDATA[Serhiy Butz]]></dc:creator>
            <pubDate>Fri, 21 Aug 2020 05:45:23 GMT</pubDate>
            <atom:updated>2022-11-02T15:21:04.499Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*36w7tvtq6BGog8vA.jpg" /></figure><p>Suppose our Combine-based app connects to an outdoor air temperature sensor, which pushes the temperature measurements at a constant rate. We want our app to show a dynamic diagram of the latest temperature readings, but we don’t need all history of them, rather only a certain number of the latest ones to build the diagram. In this post, we will develop a Combine-based solution for the described data source. Also, our data source will be capable of being reused from multiple parts of the app.</p><h3>Devising a solution</h3><p>Actually, it will immediately occur to those with a programming background in such reactive frameworks like RxSwift that the shareReplay operator is a good fit for our task, and by simply building a pipeline of the temperature sensor with it, we will achieve our goal. The shareReplayoperator does just that ― it implements the concept of a sliding window of the latest stream values. To refresh our mind, the marble diagram of the shareReplay operator is shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/755/0*rkLi2opup4UuL79y.png" /></figure><p>In general, the shareReplay operator returns a <a href="https://medium.com/@benlesh/hot-vs-cold-observables-f8094ed53339"><em>hot</em></a> publisher that has an identity (i.e., it’s a reference type). What it does is:</p><ul><li>share the upstream publisher with the downstream subscribers</li><li>buffer the latest output values from the upstream, up to a given size of replay and whenever new subscribers connect, it will replay that buffer to them</li></ul><p>Combine, however, unlike RxSwift, doesn’t offer the shareReplay operator yet. But the good news is that Combine has an open design and one way to go is to make up a custom shareReplayoperator on top of it. One simplistic, but still working implementation of the shareReplay operator is provided below <em>(you can use playgrounds in Xcode to execute the snippets from this post.)</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*KSygUCsihTBvXmtI.png" /><figcaption><a href="https://gist.github.com/serhiybutz/069ded285a2c4b6384d14b5e0049c216">Click for Gist</a></figcaption></figure><p>Let’s examine it:</p><ol><li>The class ShareReplay adopts the Publisher protocol that declares requirements for the <em>publisher</em>. The <em>publisher</em> responsibilities, apart from emitting output values and completion events to the subscribers, include a provision for the latters of a subscription, which is necessary for Combine’s backpressure-driven operation.</li><li>The class ShareReplay is initialized with the upstream publisher that is preserved as a class instance via the share operator <em>(line 14)</em>. Later on, the shared upstream publisher provides shared pipelines to new subscribers <em>(line 26)</em> — this is what makes shareReplay’s resulting publisher <a href="https://medium.com/@benlesh/hot-vs-cold-observables-f8094ed53339"><em>hot</em></a>.</li><li>The structure Record.Recording stores the stream of the upstream values <em>(lines 33-34)</em> and is used to simulate the buffer from which the latest bufferCapacity elements are replayed to each new subscriber <em>(lines 21-25)</em>.</li><li>The operator function share(replay:) is added to the Publisher type <em>(lines 40-42)</em> for seamless incorporating into Combine pipelines building, in a consistent way with the other Combine facilities.</li></ol><p>Now, the following code illustrates how we can leverage the shareReplay operator in temperature measurements diagramming.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*3fDtVFDWDWbC-8yi.png" /><figcaption><a href="https://gist.github.com/serhiybutz/fe3777a3b9a2b2af387fb32bec08b283">Click for Gist</a></figcaption></figure><p>Let’s break the above code down:</p><ol><li>For the source of temperature measurements we are using a PassthroughSubject publisher <em>(line 3)</em>.</li><li>The actual temperature measurement data source is formed by a pipeline with the shareReplayoperator <em>(lines 5-6)</em>, where we specify a count of three measurements to be replayed from the buffer to upcoming subscribers.</li><li>Set up a dummy diagramming subscription <em>(lines 9–16)</em>. This code will just log the received measurements to the console.</li><li>Simulate a few temperature measurements by sending arbitrary values to the measurementspublisher <em>(lines 13-21)</em>.</li><li>Set up another dummy subscription <em>(lines 24–31)</em>.</li><li>Simulate another temperature measurement <em>(line 33)</em>.</li><li>Send the completion event shutting down the pipeline <em>(line 34)</em>.</li></ol><p>If we run the above snippet, we’ll get the following output to the console.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*leSl_orZtKpVEzIx.png" /></figure><p>The first four lines illustrate the receiving by the first subscriber the temperature measurements simulated in <em>lines 18–21</em>. The next three lines demonstrate three measurements replaying for the second subscription. Then, there follow two lines that another simulated measurement in <em>line 33</em> has caused to demonstrate how new measurements continue to be received parallelly by both first and second subscriber. And finally, we see how the shutting down event is received by both subscribers.</p><h3>Downsides</h3><p>As already mentioned, our share(replay:) operator is a bit simplistic. Its major shortcomings are:</p><ol><li>It naively keeps track of the incoming sequence’s full history. Doing so is dangerous when incoming values come in large numbers.</li><li>It handles backpressure in a simplistic way — by requesting an unlimited number of values from its upstream, no matter what. BTW it’s odd that such behavior is observed across the entire Combine framework when there’s space for optimization. In my opinion, it contradicts Combine’s declared backpressure-driven paradigm (for more check out this <a href="https://serhiybutz.github.io/combine-insight-into-zip-operator/">blog post</a>).</li></ol><h3>Looking for a better solution?</h3><p>If you are looking for a more adult share(replay:) operator, there’s one developed by me. It features:</p><ul><li>a circular buffer for caching-related optimization</li><li>a fine-grained backpressure handling</li></ul><p>A detailed discussion of it is out of scope of this blog post. Check out its implementation in the <a href="https://github.com/serhiybutz/XCombine">XCombine repository</a>.</p><h3>Wrap up</h3><p>In this blog post we’ve explored another tricky case of using Combine in a real-world scenario and came up with a solution by developing our own share(replay:) operator.</p><p>Thanks for reading 🎈</p><p><em>Originally published at </em><a href="https://serhiybutz.github.io/"><em>https://serhiybutz.github.io</em></a><em> on February 16, 2020.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=634f2516579" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Combine: Insight into Zip operator]]></title>
            <link>https://serhiybutz.medium.com/combine-insight-into-zip-operator-6338f32ea8cb?source=rss-ed58de3f6add------2</link>
            <guid isPermaLink="false">https://medium.com/p/6338f32ea8cb</guid>
            <category><![CDATA[combine]]></category>
            <category><![CDATA[reactive-programming]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[ios-app-development]]></category>
            <category><![CDATA[zip]]></category>
            <dc:creator><![CDATA[Serhiy Butz]]></dc:creator>
            <pubDate>Thu, 20 Aug 2020 05:30:59 GMT</pubDate>
            <atom:updated>2022-11-02T15:25:28.742Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*dcveOeFmfzO6Uzbw.jpg" /></figure><h3>Intro</h3><p>Apple’s Combine, a <a href="https://en.wikipedia.org/wiki/Reactive_programming">reactive programming</a> (RP) framework, was developed for heavy use and with achieving the maximum flexibility and performance in mind. Being deeply integrated with other proprietary components, at a low level, it is closed source. Combine generally won’t be that hard to start to use for those who are already familiar with other RP frameworks. But as new software, it’s still lacking documentation and practical examples of solutions for the real-world usage scenarios.</p><p>Let’s briefly refresh our memory of what RP is about. In essence, RP is all about representing and transforming discrete value sequences (data streams). Apart from values, sequences also operate with completion and error events. Sequences split into two groups: <em>static</em> and <em>dynamic</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/763/0*cBPSMBVPmvhYXdzA.png" /></figure><p>Static sequences are those whose values are available all at once, like regular arrays. But dynamic sequence values are emitted over time and their source may be, for example, the user typing on the keyboard. Another important property of sequences is whether they are bounded-size or not.</p><p>The major reason why RP is gaining increasing popularity is the asynchronous nature of the real-world tasks, like interactive user interfaces, which are greatly modelled with dynamic sequences. In Combine a sequence is represented by the term <em>publisher</em>. It provides various publishers of both natures, dynamic (like <em>subjects</em> and <em>future</em>s), and static (like array and range <em>publishers</em>).</p><p>RP is one of the major topics of personal interest to me; therefore, I’m going to occasionally share my own insights gained in the process of Combine exploration.</p><p>In this post, I wanna bring up one specific issue that I came across when devising a zip operator-based solution for enumerating events.</p><h3>So what’s the problem?</h3><p>Say, we have some arbitrary, infinite source of events, a dynamic publisher, and need to get the events enumerated by assigning each event a unique serial number. The most straightforward approach that comes to mind is the one based on the <em>zip</em> operator.</p><p>To refresh our memory, the <em>zip</em> operator’s marble diagram is shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/676/0*3zAmmouaK3DFdlKy.png" /></figure><p>zip waits until both upstream publishers, a and b, have emitted, then delivers the oldest unconsumed event from each one together as a tuple to the downstream subscriber.</p><p>The point of the idea is introducing another publisher, a static one, like (0..&lt;100).publisher, to produce serial numbers, then combining both of them with the <em>zip</em> operator into a single pipeline. The following example illustrates the idea <em>(you can use playgrounds in Xcode to execute the snippets from this post.)</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*m11jXpVdTFHR5vQR.jpg" /><figcaption><a href="https://gist.github.com/serhiybutz/96eac312b4c9d8ed5f24936aa90ba2d1">Click for Gist</a></figcaption></figure><p>The above code produces the following output to the console.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ImpK6vqdHbFYgsXs.png" /></figure><p>The solution is simple and clear. So far, so good, our code works. However, because the serial number publisher in our example is bounded-size (limited by a quantity of 100 values (<em>line 5</em>)), the code stops execution after enumerating the maximum of a hardcoded specific number of values. To correct the problem let’s remove the upper bound from the serial number publisher’s range by re-writing it as (0...).publisher, and thus converting it into an unbounded-size publisher.</p><p>Now, if we run the code, we’re going to find the pipeline in a never-ending loop producing an infinite sequence of serial numbers printed out to the console. Why is that? To find out what’s causing the problem it makes sense to try analyzing the output of the debugging operator <em>print</em> for both the serial number publisher <em>(line 5)</em> and input event publisher <em>(line 7)</em>. Let’s modify the example as shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ZmBaHQGxYfR_7eGH.jpg" /><figcaption><a href="https://gist.github.com/serhiybutz/0c384f7dae075aa21604105a421a64e7">Click for Gist</a></figcaption></figure><p>Now, after running the code again with breaking the execution after a while, let’s check out the top of the console output.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*d-HIkBAwcTl1ZpkU.png" /></figure><p>The first two lines indicate passing the subscription from both of the publishers. The third and fourth lines indicate making by the <em>zip</em> operator demand request for <em>unlimited</em> number of values for <em>both </em>publishers. And now it seems to make sense: as soon as the serial number publisher obtains control it never stops emitting values in satisfying the infinite demand request. With finite demand, this works alright, because when the serial number publisher finishes, the entire sequence is buffered and then those numbers are used for pairing up with the source values.</p><p>But why does Combine’s <em>zip</em> operator ever send its upstreams the <em>unlimited</em> demand request? Well, we can assume that it just forwards, upstream, the requested demand from its downstream subscriber, which is the <em>sink</em> operator, known to send the <em>unlimited</em> initial demand. To check if this hypothesis is true we’ll need to be capable of explicitly specifying the initial demand by the subscriber. And we’re going to take advantage of a custom <em>sink</em> instead of Combine’s provided one, whose code can be found <a href="https://github.com/serhiybutz/blog-samples/blob/master/Misc/CustomSink.swift">here</a>. The following code is the updated example from above with the custom <em>sink</em> in place to specify a <em>finite</em> initial demand of 5 values <em>(line 13)</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*asXdGscUMlH2bwGN.jpg" /><figcaption><a href="https://gist.github.com/serhiybutz/667acb426d2fbfd1cd58656e3134f474">Click for Gist</a></figcaption></figure><p>Now, the code executes successfully, without any hanging up. Here’s its full output from the console.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*n4vrG2mKVAvHfH3Q.png" /></figure><p>Of what’s new, first, we see that both publishers’ demand requests now have a <em>finite</em> value, 5. Next, there follow 5 values emitted by the serial number publisher. Finally, we can observe how the control is passed to the input event publisher which emits 2 values, “foo” and “bar”, each followed by the <em>zip </em>operator’s emission. So, our hypothesis proves true: Combine’s <em>zip</em> operator just forwards the demand received from its subscriber!</p><p>Is this behavior absolutely correct for the <em>zip</em> operator? Well, undoubtedly Apple had good reasons for implementing the <em>zip</em> operator this way, still, I find this odd, because this is an example of when Combine’s <em>static</em> and <em>dynamic</em> publisher just don’t fit well together.</p><h3>The scan-based solution</h3><p>For event enumeration, we can always go for another simple approach based on the <em>scan</em> operator which has proved to work well on Combine in all situations.</p><p>To refresh our memory, the <em>scan</em> operator’s marble diagram is shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/755/0*bfjIdJNuJRh12Suv.png" /></figure><p>scan transforms elements from the upstream publisher by providing the current element to the closure along with the last value returned by the closure.</p><p>The scan-based code for event enumeration is provided below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ZOvg9ZTlX8j2kVq2.jpg" /><figcaption><a href="https://gist.github.com/serhiybutz/4248e25f41c8a21643763f12fd4b527d">Click for Gist</a></figcaption></figure><p>In the code above, we are using a stateful <em>scan</em> operator to keep track of the latest issued serial number in the accumulator and deliver it in pairs (as tuples) with its corresponding input value to the downstream subscriber.</p><h3>The alternatively behaved zip solution</h3><p>I believe the intuitive behavior for the <em>zip</em> operator would be the following: whatever demand <em>zip </em>receives from its downstream (except for 0, in which case it should also send 0 upstream), it should always send a demand for only one value to its upstreams, then wait for the response from each of them, then emit the result downstream, closing the round. And repeat the rounds until the demand gets exhausted.</p><p>I‘ve developed an alternative to Combine’s original <em>zip</em> operator, which behaves in the manner described above and is applicable for enumerating any values, no matter whether the source publisher is finite or infinite. This solution allows seamless combining both worlds ― <em>dynamic</em> and <em>static</em> publisher when the <em>zip</em> operator is concerned. However, a detailed discussion of it is out of scope of this blog post. It is available in the <a href="https://github.com/serhiybutz/XCombine">xCombine repository</a> where you can check its source code out. The example demonstrating it is shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*l8oHNbowvVtLL660.jpg" /><figcaption><a href="https://gist.github.com/serhiybutz/df8ea42aa5f0149e193c2a6f733af634">Click for Gist</a></figcaption></figure><p>Notice how in the example we are opting for xCombine’s version of the <em>zip</em> operator by prepending it with the x property <em>(line 9)</em>.</p><h3>Wrap up</h3><p>In this blog post, we’ve looked into the odd behavior of Combine’s <em>zip</em> operator in one of the common real-world usage scenarios and explored a couple of solutions.</p><p>Thanks for reading 🎈</p><p><em>Originally published at </em><a href="https://serhiybutz.github.io/"><em>https://serhiybutz.github.io</em></a><em> on November 7, 2019.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6338f32ea8cb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Shared Theme Manager]]></title>
            <link>https://serhiybutz.medium.com/shared-theme-manager-282fa59b8399?source=rss-ed58de3f6add------2</link>
            <guid isPermaLink="false">https://medium.com/p/282fa59b8399</guid>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[target-action]]></category>
            <category><![CDATA[reusable]]></category>
            <category><![CDATA[themes]]></category>
            <category><![CDATA[ios]]></category>
            <dc:creator><![CDATA[Serhiy Butz]]></dc:creator>
            <pubDate>Tue, 11 Feb 2020 08:57:09 GMT</pubDate>
            <atom:updated>2022-11-02T15:37:42.673Z</atom:updated>
            <content:encoded><![CDATA[<h3>Swift: Developing a Shared Theme Manager</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Q--f3UnkcqItPj75.jpg" /></figure><h3>Table of Contents</h3><ul><li><a href="#5631">Introduction</a></li><li><a href="#3248">UIAppearance technology?</a></li><li><a href="#85f1">What is a theme in the first place?</a></li><li><a href="#c9ed">Theme model</a></li><li><a href="#0aae">Theme manager</a></li><li><a href="#ef25">Notifying via Observer</a></li><li><a href="#fb6a">Swift-y Target-Action for flexibility</a></li><li><a href="#1bcf">Turning into a shared component</a></li><li><a href="#351f">Wrap up</a></li></ul><h3>Introduction</h3><p>For today’s apps support for both light and dark appearances that users can toggle between has become the standard. While the light appearance, known as <em>Light Mode</em>, remains a classic theme, the appeal of the dark appearance, known as <em>Dark Mode</em>, is growing. Apart from having a more aesthetic look, <em>Dark Mode</em> is easier on your eyes for reading in dark ambient lighting conditions. And it also <a href="https://www.thejournal.ie/black-background-battery-power-2700675-Apr2016/">drains the battery less on OLED screens</a>. Nonetheless, support for the classic <em>Light Mode</em> is still actual, because, for example, it is better for reading in bright ambient lighting conditions. Consequently, we as app developers should ensure users have the possibility to choose a theme appropriate to their environment.</p><p>In September 2019 Apple finally released iOS 13 with full, system-wide <em>Dark Mode</em> support. Users can toggle between <em>Light</em> and <em>Dark modes</em> from a device’s settings and opt for desired interface style, and the system then uses an appropriate color palette for all screens, views, menus, and controls.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/868/0*Gd3x1ppqwrTfzv2P.png" /></figure><p>When developing our apps, by using <a href="https://developer.apple.com/documentation/uikit/uicolor/ui_element_colors">semantically defined colors</a>, <a href="https://developer.apple.com/documentation/xcode/supporting_dark_mode_in_your_interface#2993897">custom color assets</a>, and <a href="https://developer.apple.com/documentation/uikit/uiimage/providing_images_for_different_appearances">custom image assets for different appearances</a>, we achieve the automatic adaptation of the app interface to a chosen system-wide mode. There is also a nice <a href="https://developer.apple.com/videos/play/wwdc2019/214/">Apple’s WWDC Dark Mode introductory talk</a>.</p><p>Nonetheless, there is still a huge amount of pre-iOS 13 devices in use, that do not have on-board <em>Dark Mode</em> support and it is not yet time to forget about them for good. For that reason, we still have to come up with a solution that works even for pre-iOS 13 devices.</p><h3>UIAppearance technology?</h3><p>As long ago as 2011, Apple addressed the app theming with <a href="https://developer.apple.com/documentation/uikit/uiappearance">UIAppearance</a>. Unfortunately, UIAppearance is not a big helper for us, as it hardly has upsides other than not needing to use a third-party library, while its downsides are:</p><ul><li>It does not allow toggling between themes “on the fly”. UIAppearance was designed to apply appearances only <a href="https://developer.apple.com/documentation/uikit/uiappearance#overview">once in a lifetime</a>, before a view is added to a window.</li><li>UIAppearance is designed mostly for UIView subclasses, with some exceptions, like UIBarItem. But how can it be useful in the case of, say, CALayer?</li><li>It is not concerned with theme semantics being a mere description of concrete UI element appearances, not so much as the <a href="https://en.wikipedia.org/wiki/Look_and_feel">look and feel</a> in its own right (more on this below).</li></ul><p>So let’s go ahead and develop a better solution! We are going to start off with building up an idea of a <em>theme</em> as such.</p><h3>What is a theme in the first place?</h3><p>In general, a <em>theme</em> is a concept of appearance that apps’ UI elements adhere to. An app can provide different themes for the users to choose from, and the one chosen, a <em>current theme</em>, is a <a href="https://en.wikipedia.org/wiki/Single_source_of_truth">single source of truth</a> for rendering the app’s entire interface appearance.</p><p>A <em>theme</em> is a collection of <em>themes attributes</em>, which should be defined in their own semantics, with clear intent, in terms of the UI in its entirety. An example of an aspect to represent with a theme attribute would be the background color or typeface across the whole app. The overall appearance characteristics of the user interface are commonly expressed with such categories as:</p><ul><li>Layout: Width, height, margin, floating or not, positioning, etc.</li><li>Font properties: Size, weight, etc.</li><li>Appearance: Colors, etc.</li></ul><p>Each UI element renders its appearance by referring to theme attributes translating the abstract theme semantics into the one of itself.</p><p>Now that our underlying reasoning and subject area have been established, we are prepared for the goal of this post ― going through the steps of planning and developing the program code for our theme managing solution.</p><h3>Theme model</h3><p>We are going to encapsulate a set of available theme attributes in the <em>theme model</em>. Distinct instances of the theme model will represent different themes.</p><p>Let’s start off by defining our example theme model, as shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*t5062vovRBNv9ZzS.jpg" /><figcaption><a href="https://gist.github.com/serhiybutz/0947bcdffa8da0079f2cd940289f21e2">Click for Gist</a></figcaption></figure><p>We have used a value type, struct, to represent the theme model. Its properties will serve as the theme attributes. Our example theme model has got 3 of them:</p><ul><li>appBgColor for the app background color</li><li>highlihtedBgColor for the highlighted text background color</li><li>textColor for the normal text color</li></ul><p>See how the theme attributes are different from concrete UI element attributes — they describe the appearance in general, i.e., they know nothing about concrete UI elements and bear the theme’s own semantics.</p><p>For the next step we are going to define our example themes. It’s convenient in <em>Swift</em> to retroactively encapsulate them as static properties right in the MyThemeSettings struct, with an extension.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*2NySdBkBf3fJ5v-k.jpg" /><figcaption><a href="https://gist.github.com/serhiybutz/c3d38ad0fdf015036177c45dddeef949">Click for Gist</a></figcaption></figure><p>Here we have got the instances lightTheme and darkTheme for the light and dark themes, respectively.</p><p>For the means of referencing our themes from across the app, it is handy to make use of an enum, as shown in the example below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*8dGT6DB6oyKtfaev.jpg" /><figcaption><a href="https://gist.github.com/serhiybutz/e060258be74e74608699a23e24962413">Click for Gist</a></figcaption></figure><p>The above enum has got two cases light and dark for our light and dark themes, which behave much like “tags”, each representing its related theme instance; the enum’s computed property settings is responsible for the mapping.</p><p>With such an enum, dealing with themes in code will be a breeze. For example, referencing a theme in a variable is as easy as setting it to one of the enum’s case labels, for example, var currentTheme: MyTheme = .dark. Getting to the theme attributes, for example, to the text color, would then be, like currentTheme.settings.textColor. Convenient, right?</p><p>And now let’s proceed with our theme managing code itself.</p><h3>Theme manager</h3><p>First of all, the last thing we want for our theme managing code ― to be scattered throughout the app. In order for the codebase to be maintainable, we have to design to the <a href="https://en.wikipedia.org/wiki/Separation_of_concerns">SoC principle</a>. It means we should concentrate our theme managing code in one place. We are going to call it a <em>theme manager</em>. Let’s outline its responsibilities:</p><ol><li>maintain the available themes</li><li>provide the <em>current theme</em> to the themable UI elements (later on ― <em>themable objects</em>) for reference</li><li><em>notify</em> the themable objects about changes of the current theme (by using some notification mechanism)</li></ol><p>Now let’s consider the theme manager from the perspective of accessing it from the other parts of the app. Structurally, the theme manager is a <em>dependency</em> of the themable objects, because it is them who consult it as to how to render themselves. But as a software component in its own right, the theme manager is totally independent of them. And what’s more, it is also a so called <a href="https://enterprisecraftsmanship.com/posts/singleton-vs-dependency-injection/#_singleton_vs_dependency_injection"><em>ambient dependency</em></a> because of arbitrarily spanning across multiple parts of the app.</p><p>This, along with the 2 reasons below justifies using <a href="https://en.wikipedia.org/wiki/Singleton_pattern">Singleton Pattern</a> for <em>theme manager</em> instantiation and integration with the client app:</p><ul><li>There is no reason to have multiple instances of the <em>theme manager</em> at once.</li><li>Not only does not the <em>theme manager</em> interfere with the app domain logic, but it does not share the app domain state, thus not impeding the app testability.</li></ul><p>Besides, because of such architecture, unlike UIAppearance, this solution does not impose any limitation on which classes of themable objects it can be used with.</p><p>Now that we have laid the foundation, we are ready for proceeding with theme manager developing. We are going to walk through 3 stages of theme manager evolution — from the simplest to the advanced.</p><h3>Notifying via Observer</h3><p>The principal part of the theme manager is the notification mechanism by which the themable objects get to know when the current theme’s toggling occurs for them to update their appearance. Here is where <a href="https://en.wikipedia.org/wiki/Observer_pattern">Observer Pattern</a> comes in.</p><p>A tricky aspect about <em>Observer</em> pattern when dealing with it from <a href="https://docs.swift.org/swift-book/LanguageGuide/AutomaticReferenceCounting.html">ARC</a>-based languages, like <em>Swift</em>, is that to avoid retain cycles we need to keep observer references weakly. <em>Swift</em> offers a handy facility for this, the collection <a href="https://developer.apple.com/documentation/foundation/nshashtable">NSHashTable</a> with <a href="https://developer.apple.com/documentation/foundation/nshashtable/1412241-weakobjects">weakObjects</a>, which we are going to take advantage of. Its prominent advantages are:</p><ul><li>There is no need for manually taking care of memory management.</li><li>It is very effective: it adds and accesses objects in constant time, <em>O(1)</em>.</li></ul><p>Let’s start with creating a Themable protocol, that declares an API for the themable objects (i.e., the observers), which is going to be the type of NSHashTable’s stored elements, as shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*3y8l99fz6BgAcDhp.jpg" /><figcaption><a href="https://gist.github.com/serhiybutz/e2ac4e360c408f92b6d6d04610bd3559">Click for Gist</a></figcaption></figure><p>The only requirement of the Themable protocol is the applyTheme(_:) method, which is to be implemented by the observers, the themable objects. It will be called by the theme manager on every registered observer whenever the current theme toggles. applyTheme(_:) is the very method from which the themable objects will update their appearance and we are going to call it a <em>theme handler</em>.</p><p>Notice the @objc attribute in front of the protocol definition. It is to tell <em>Swift</em> that the protocol should be <a href="https://docs.swift.org/swift-book/LanguageGuide/Protocols.html#ID284">compatible with <em>Objective-C</em></a> (<em>line 1</em>), what is the requirement for NSHashTable’s stored elements.</p><p>Now, let’s define a class for the theme manager, called ThemeManager, as shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*PjOhX_W703MxhJYG.jpg" /><figcaption><a href="https://gist.github.com/serhiybutz/7ab4e40aa17dbf264e2102a7aeca73cf">Click for Gist</a></figcaption></figure><p>In our above theme manager, the current theme is held in the theme property <em>(line 7)</em>. Whenever we need to switch the current theme, we would just set this property to another theme enum case and the didSet property observer will respond by triggering the apply() method for theme change notifying, which will iterate through all stored observers calling their method applyTheme() <em>(lines 33-35)</em>.</p><p>Now check out how <a href="https://en.wikipedia.org/wiki/Observer_pattern">Observer Pattern</a> is implemented:</p><ul><li>the themables property <em>(line 4)</em> is the storage for the observers</li><li>the register(_:) method <em>(line 27-30)</em> is how new observers are registered</li><li>the apply() method <em>(line 32-36)</em> is how the observers are actually notified</li></ul><p>As mentioned, with <a href="https://en.wikipedia.org/wiki/Singleton_pattern">Singleton Pattern</a> <em>(lines 14–21)</em> we are instantiating and maintaining a single instance of the theme manager.</p><p>Also, notice that the observer-notifying method applyTheme() is initially executed <em>(line 29)</em> right in the observer registration in order to apply the default theme. This implies that the observers should be ready for applying the theme at the <em>call sites</em> (where the method register(_:) is invoked). For example, for a view controller, a proper place for register(_:) invoking would be in the viewDidLoad() method.</p><p>Now we need a bit updated version of the originally introduced example of the enum MyTheme, as shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*QP1lBA4NtX42PNkP.jpg" /><figcaption><a href="https://gist.github.com/serhiybutz/31ed757f32fc419042dbb21db46e41da">Click for Gist</a></figcaption></figure><p>In the above code, in contrast to the original enum, we have declared it with a raw type of Int and prefixed it with the <a href="https://developer.apple.com/swift/blog/?id=22">@objc</a> attribute <em>(line 1)</em>, or otherwise, the compiler would yell: <em>“Method cannot be a member of an @objc protocol because the type of the parameter cannot be represented in Objective-C”</em>.</p><p>That’s it, our theme manager is completed. At this point, the themable objects can apply theming, as in the example shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*bNFP5ud0jtV39cjR.jpg" /><figcaption><a href="https://gist.github.com/serhiybutz/188906a6a54570a5ce6ec602dbdd9a42">Click for Gist</a></figcaption></figure><p>For the purpose of illustrating the use of our theme manager, we have customized by subclassing a view controller naming it DemoViewController <em>(line 28)</em>. It simply displays an instance of an also customized by subclassing text label, HighlightedLabel <em>(line 4)</em>.</p><p>By adopting the Themable protocol, the HighlightedLabel class <em>(line 12)</em> and DemoViewController class <em>(line 39)</em> have become valid themable classes, instances of which can be registered with our theme manager. The HighlightedLabel class is registering its instances from didMoveToWindow() method <em>(line 7)</em> and the DemoViewController class ― from its viewDidLoad() method <em>(line 35)</em>, both early in their lifecycle.</p><p>As mentioned before, during the process of registering themable objects, the theme manager performs initial execution of the applyTheme(_:) method of those, i.e., their theme handler. In the given code the theme handlers are defined in the extensions adding the Themable protocol conformance <em>(lines 14-24, 41-43)</em>. The applyTheme(_:) method will be called by the theme manager every time whenever the current theme changes.</p><p>Find an example of the complete demo app <a href="https://github.com/SergeBouts/blog-samples/tree/master/ThemeManagerDemo-Observer">here</a>.</p><p>Now let’s see if we can make things a bit more interesting. Our theme manager works just fine. It can also provide more flexibility by using subclassing in such a manner when a subclass refines theming, done in its superclass. However, there are times when we need a higher flexibility degree than that, like when our app interface uses specific, say, text labels that need to appear different from the others for the same theme, or, in other words, when we need a per-instance theming granularity. It means that the level of dynamism our solution provides is insufficient, and we might go for a more runtime-oriented solution with fewer compile-time restrictions on theme handling code. So, let’s go ahead and level up our theme manager.</p><h3>Swift-y Target-Action for flexibility</h3><p>Getting the desired theming flexibility with a per-instance theming granularity requires us to be able to loosely define multiple theme handlers in order to provide them for different instances. Mere abstracting out of the themable observers (via Themable protocol adherence) with a unified theme handler method is too restrictive and so inappropriate any more. And we have at our disposal the following 2 facilities with the sufficient level of dynamism:</p><ul><li><a href="https://docs.swift.org/swift-book/LanguageGuide/Closures.html"><strong>Closures</strong></a>. <em>Closures</em> are self-contained blocks of functionality that can be passed around and used in our code.</li><li><a href="https://en.wikipedia.org/wiki/Target%E2%80%93action"><strong>Target-Action</strong></a>. In essence, <em>Target-Action</em> is a mechanism that allows sending an <em>action</em> (or message) to a certain <em>target</em> when an even occurs.</li></ul><p><em>Closures</em> are extremely flexible and prominently used in <em>Swift</em> everywhere. Still, the code using closures sometimes can be prone to strong reference cycles incurring the overhead of maintaining <a href="https://docs.swift.org/swift-book/LanguageGuide/AutomaticReferenceCounting.html#ID56">capture lists</a> on you, thus resulting in the app’s theming code being more complex and also a bit untidy when compared to the Target-Action technique. For that reason, I find the Target-Action technique more preferable for our task.</p><p>Although <em>Target-Action</em> originates from <em>Objective-C</em>, there also happens to exist a <a href="https://oleb.net/blog/2014/07/swift-instance-methods-curried-functions/"><em>“Swift-y” version of Target-Action</em></a>, which is based on the <em>“Currying”</em> nature of <em>Swift</em> instance methods. This makes trying out this technique in practice especially interesting. So, now we are going to update our theme manager to employ <em>Swift-y Target-Action</em>, where the <em>target</em> will represent a themable object and <em>action</em> ― a theme-handling method.</p><p>While our original theme manager stored the references to the themable objects, now it will need to store the <em>target-action</em> pairs, which will represent the theme handlers from now on. As per <a href="https://oleb.net/blog/2014/07/swift-instance-methods-curried-functions/"><em>Swift-y Target-Action</em></a> pattern, we need to declare the TargetAction protocol and define the AnyTargetActionWrapper struct adopting it, as shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*XMGwCKUqntYYC_iw.jpg" /><figcaption><a href="https://gist.github.com/serhiybutz/49f7fefa4d7dc42d63b1e72b4a39d886">Click for Gist</a></figcaption></figure><p>Basically, the AnyTargetActionWrapper struct is a container for a <em>target-action</em> pair. Let’s break it down:</p><ul><li>It is generic, parameterized by its stored target’s type T; it employs <a href="https://medium.com/@bobgodwinx/swift-associated-type-design-patterns-6c56c5b0a73a"><em>type erasure</em></a> to hide the actual type of the target.</li><li>It references the stored target weakly preventing retain cycles <em>(line 6)</em>.</li><li>It stores the action in the <em>curried</em> form, i.e., in the form of a closure taking the target as the first parameter, thus making up the target’s instance method reference, which then takes its declared parameters <em>(line 7)</em>. For more details, check out the <a href="https://oleb.net/blog/2014/07/swift-instance-methods-curried-functions/">Swift-y Target-Action article</a>.</li></ul><p>So far, so good, but now comes the question: where should we store theme handlers? The critical factor is that the lifetime of multiple theme handlers should be tied with that of their related targets. Previously, with the Themable protocol adherence, we referred to a theme handler through a themable object reference. Because those references were stored in a <a href="https://developer.apple.com/documentation/foundation/nshashtable">NSHashTable</a> (with <a href="https://developer.apple.com/documentation/foundation/nshashtable/1412241-weakobjects">weakObjects</a>) themable storage, when a themable object deallocated, its reference automatically removed from the storage. But now, it is the lifetime of a whole group of theme handlers that depend on a target, rather than that of an individual theme handler. And so we should come up with a solution for storing separate groups of theme handlers for individual targets.</p><p><em>Swift</em> is very powerful and one of its outstanding capabilities is <a href="https://www.e-gineering.com/2019/07/31/swift-essentials-protocols/#:~:text=Protocol%20Extensions">retroactive modeling through the use of protocol extensions</a>. It allows declaring a protocol, extending it with some functionality, and by <a href="https://docs.swift.org/swift-book/LanguageGuide/Protocols.html#ID278">declaring protocol adoption with an extension</a>, easily “injecting” that added functionality into an arbitrary type ― it looks like the most elegant solution. Thus, for our task, we could declare, for example, a ThemableStorage protocol, use <em>Swift</em> extensions to add a property for the theme handler storage to this protocol, and then, by declaring that protocol adoption for a themable object’ type, we could easily attain what we need ― a theme handler storage’s lifetime tied with that of the targeted themable object. Unfortunately, this is not the case, because, as for now, <em>Swift</em> lacks the support of adding <em>stored</em> instance properties with an extension.</p><p>For our task, <em>Associated Objects</em> will come to the rescue. This facility is based on the <em>Objective-C</em> runtime function objc_setAssociatedObject() which allows making associations between one object and others, distinguished by unique associated keys. Its counterpart function, objc_getAssociatedObject(), is to retrieve a previously established association by the associated key. And this is how we are going to tie theme handler storages’ lifetimes with their related targets. Let’s write a class for our theme handler storage, called TargetActionStorage, encapsulating the said mechanism as well as taking over the notifying of the stored theme handlers, as shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*EzA7awQ3vsrtGgQZ.jpg" /><figcaption><a href="https://gist.github.com/serhiybutz/8c1a180392b6ccbd7f47d452cdd2f641">Click for Gist</a></figcaption></figure><p>In the first place, the above class has two static methods for instantiating and retrieving targets’ associated storages for theme handlers, setup(for:) and get(for:), which both take a targeted object as an argument. In essence, these methods are wrappers over objc_setAssociatedObject() and objc_getAssociatedObject(), respectively. For the associated key, we are using a reference to a unique string value in the mutable global variable associatedKey <em>(line 3)</em>.</p><p>Next comes <em>Observer Pattern</em>’s part <em>(lines 6, 24–38)</em>, which comprises the following instance methods:</p><ul><li>register(target:action:initialTheme:) This method wraps up and stores the passed target-action pair in the targetActions property <em>(line 6)</em>, and then executes the passed action to initially apply the current theme passed in the initialTheme argument.</li><li>applyTheme(_:) Whenever the current theme changes, the theme manager would invoke this method to notify the stored theme handlers. It iterates through the targetActions array and runs the stored actions. This method takes a new current theme as the theme parameter.</li></ul><p>Now let’s go ahead and finally update our theme manager, as shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*JgOy0JakhSzTM4Fu.jpg" /><figcaption><a href="https://gist.github.com/serhiybutz/3bca5b9b1679b2db9af0d52628e3e4d9">Click for Gist</a></figcaption></figure><p>In the above theme manager, in contrast to the original version, except for changing the storage property name to targetActionStorages and its element type to TargetActionStorage <em>(line 4)</em>, there has significantly changed the lower part <em>(lines 27-46)</em>.</p><p>Now, when the register(target:action:) method gets called to register a new theme handler, it first obtains the passed target’s associated storage by either retrieving an existing one <em>(line 32)</em> or instantiating a new one <em>(line 35)</em>. Then it delegates registering the new theme handler to the obtained storage (<em>line 39</em>). Besides that, whenever a new storage gets created, it is also weakly preserved in targetActionStorages (<em>line 36</em>).</p><p>Similarly as before, upon the current theme change, the theme property observer triggers theme handler notifying by calling the apply() method. But now, the storages preserved in the targetActionStorages property are iterated through to run their stored theme handlers for a new current theme (<em>lines 43-45</em>).</p><p>BTW, here we have used the original MyThemeModel and MyTheme, introduced in <a href="#c9ed">Theme model section</a>, with no changes.</p><p>Now that the new theme manager has been designed, let’s see how it can be integrated with themable objects in practice to illustrate the advantages of this approach.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*eU-oIE54u5_15GLH.jpg" /><figcaption><a href="https://gist.github.com/serhiybutz/a349b77e3662dac2787860b319a8d6ea">Click for Gist</a></figcaption></figure><p>In the code above, first off, we don’t need anymore any Themable protocol adherence for our UI elements to be themable objects.</p><p>Our DemoViewController has not changed fundamentally. We have defined its single theme handler applyTheme(_:) in an extension <em>(lines 23-25)</em> and registered it with the theme manager from the viewDidLoad() method <em>(line 10)</em>, similarly as before. Overall, it is no different from the previous customizing by subclassing to add theming.</p><p>However, things have gone differently for the highlighted label. In the same source file as for DemoViewController we are extending the UILabel class to add the applyHighlightedLabelTheme(_:) method to be a theme handler for our instance of the highlighted label. We are also registering it with the theme manager from the view controller’s viewDidLoad() method <em>(line 15)</em>. This, along with the use of the scope isolating fileprivate access modifier for the label’s theme handling method <em>(line 30)</em>, has the effect of theming with a per-instance granularity, when we can apply theming just to specific instances of a themable object, not so much as for the whole class. Such an elegant per-instance theming allows us to reinforce the <a href="https://en.wikipedia.org/wiki/Separation_of_concerns">SoC principle</a>. Notice, that we could just as well have had multiple differently-named theme handlers defined for the same instance.</p><p>Find a complete example of the app demonstrating our <em>Swift-y Target-Action</em>-based theme manager <a href="https://github.com/SergeBouts/blog-samples/tree/master/ThemeManagerDemo-SwiftyTargetAction">here</a>.</p><p>Now, time for the bonus round. We have developed a pretty flexible theme manager, so far, but let’s go even further and think about it from the code organization perspective. Any application consists of a bunch of different by functionality components; the cleaner responsibilities and better isolation of the components from one another, the more <em>reusable</em>, <em>testable</em>, <em>maintainable</em>, or in one word ― <a href="https://en.wikipedia.org/wiki/Modular_programming"><em>modular</em></a> they are. Besides, it is common for a well-designed component to be even <em>shared</em> across multiple projects, and our theme manager is a good candidate for such a <a href="https://itnext.io/how-to-easily-reuse-components-across-projects-and-repositories-fa73f8ba2a83"><em>shared</em> component</a> too.</p><h3>Turning into a shared component</h3><p>Even though our theme manager encapsulates theming-related functionality with well-defined responsibilities, it hardly makes a <em>shared</em> component so far because it is tightly coupled to the client app. The critical point is that it is dependent on concrete types, the MyThemeSettings struct and MyTheme enum, that belong to the client app’s <em>domain</em> logic. This problem can be fixed by abstracting those types out, so as the theme manager code would not refer to the client app’s types, making the theme manager and the client app loosely coupled. So, let’s go ahead and level up our theme manager by evolving it into a <em>shared</em>-ready, robust component.</p><p>Basically, the code is not going to change dramatically from the preceding one, for the most part; in essence, it is a mere generifying of the previous version’s types. So, I am just going to present the updated snippets from before and briefly comment on what has changed.</p><p>First and foremost, in our preceding theme manager, wherever we referenced the client app’s MyThemeSettings struct and MyTheme enum, we will need to transition to referencing the protocols ThemeModelProtocol and ThemeProtocol instead, which are presented below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*7mCFXPmwejPJgyPk.jpg" /><figcaption><a href="https://gist.github.com/serhiybutz/35f4d0f3429e6cb3359b60f81e37c733">Click for Gist</a></figcaption></figure><p>Besides, the above two protocols are to be adopted by the client app’s theme model struct and theme enum, respectively. With such a design, we will decouple our theme manager code from the client app, and both of them will depend on the same abstractions ― protocols.</p><p>In the above code, in the ThemeProtocol protocol declaration, we are referencing the client app’s actual theme model type <em>(line 5)</em> via the <em>associated type</em> Model (<em>line 4</em>), meaning that ThemeProtocol has become an <a href="http://www.russbishop.net/swift-associated-types">abstract protocol</a>, with all its implications.</p><p>The ThemeProtocol’s conformance to Equatable makes the theme enum cases comparable.</p><p>As already mentioned, the types MyThemeSettings and MyTheme, which are on the client app’s side, should conform to the just-introduced protocols, as in the example below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*pIoCO2m25H_QoZtY.jpg" /><figcaption><a href="https://gist.github.com/serhiybutz/68a50db55be7ef752719acd95cd5c952">Click for Gist</a></figcaption></figure><p>In the above code, for the MyTheme enum, the compiler is capable of inferring ThemeProtocol’s associated type Model eliminating the need for the use of typealias.</p><p>Next up, let’s adapt the preceding theme manager’s TargetAction protocol and AnyTargetActionWrapper struct to fit in with our above protocols, as shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*2ETRhx1IzZFJdaxO.jpg" /><figcaption><a href="https://gist.github.com/serhiybutz/e613405302c1b5ac35d9e7fbfbb0df31">Click for Gist</a></figcaption></figure><p>In the above code, the TargetAction protocol has become abstract because of introducing the associated type Theme to represent the client app’s actual theme enum. The AnyTargetActionWrapper struct has become generic, parameterized by the type parameter Theme, which is for the same reason.</p><p>Next up, let’s update the TargetActionStorage class, as shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*m-m3o_pSOBzmVFN3.jpg" /><figcaption><a href="https://gist.github.com/serhiybutz/eb7519158a4f8a26335307817ae302f2">Click for Gist</a></figcaption></figure><p>In the above code, the same type parameter Theme (to represent the client app’s actual theme enum type) has been introduced too, which is passed through to the targetAction property definition to specialize the target-action storage elements’ generic type (<em>line 6</em>). Also, Theme has replaced the previously used concrete theme enum type in the type annotation of:</p><ul><li>the two arguments of the register(target:action:initialTheme:) method <em>(lines 26, 27)</em></li><li>the argument of the applyTheme(_:) method <em>(line 34)</em></li></ul><p>Finally, let’s update our theme manager generifying it with the same type parameter Theme and renaming it to Themer, as shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*PYP8M_r6Iu6hPPxF.jpg" /><figcaption><a href="https://gist.github.com/serhiybutz/7232f5aa3677f4e49da0dcbbdfbd0934">Click for Gist</a></figcaption></figure><p>In the above code, the type parameter Theme has been passed through to the targetActionStorages property definition to specialize its stored element’s generic type (via the use of the TargetActionStorageType typealias) (<em>line 6</em>), as well as it has replaced the previously used concrete theme enum type in the type annotation of:</p><ul><li>the theme property <em>(line 9)</em></li><li>the initializer’s defaultTheme argument <em>(line 16)</em></li><li>the action argument of the register(target:action:) method <em>(lines 22)</em></li></ul><p>The other important change is that we have got rid of the singleton code from the theme manager class because it does not agree well with the theme manager reusability. Instead, we will have to place it somewhere in the client app, as shown in the code below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*7zuzEFjNQNOAesff.jpg" /><figcaption><a href="https://gist.github.com/serhiybutz/956c8362d4688160054174d02fe9a1ec">Click for Gist</a></figcaption></figure><p>In fact, the last code snippet represents the “integration point” between the client app and our shared theme manager.</p><p>That’s it. Our <em>shared</em>-ready theme manager is done now. Making a module out of it is beyond the scope of this post, though it’s trivial. You can find the git repo of our shared-ready theme manager <a href="https://github.com/serhiybutz/Themer">here</a>, which also addresses some other necessities of real-world apps, like thread-safety, which are beyond the scope of this post as well.</p><p>A final complete example of the app, demonstrating the use of our shared-ready theme manager is available <a href="https://github.com/serhiybutz/blog-samples/tree/master/ThemeManagerDemo-Reusable">here</a>.</p><h3>Wrap up</h3><p>In this article, we have created and honed a universal app theming solution by developing a robust, shared-ready theme manager, that works well both on iOS 13, featuring the system-wide Dark Mode, and on older iOS versions. Our theme manager allows easy toggling the current theme across the whole app. We started off with simple <em>Observer</em>-based notifying. Then we introduced <a href="https://oleb.net/blog/2014/07/swift-instance-methods-curried-functions/"><em>Swift-y Target-Action</em></a> theme handlers to achieve greater flexibility and reinforce the <a href="https://en.wikipedia.org/wiki/Separation_of_concerns">SoC principle</a>. And finally, we abstracted our theme manager out and made a reusable software component out of it, ready for the use across multiple apps.</p><p>Hope you found this post interesting and useful for your projects. If you have anything additional to share on this subject, please leave a comment below. I would love to hear your thoughts and findings.</p><p>Thanks for reading! 🙂</p><p><em>Originally published at </em><a href="https://serhiybutz.github.io/"><em>https://serhiybutz.github.io</em></a><em> on October 11, 2019.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/868/0*FP7GeIpXSFc1eJPN.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=282fa59b8399" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>