<?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 Samuel Adorni on Medium]]></title>
        <description><![CDATA[Stories by Samuel Adorni on Medium]]></description>
        <link>https://medium.com/@samuel.adorni?source=rss-7d0485151701------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*HSI8nZeFun9atEpf-xIDCw.jpeg</url>
            <title>Stories by Samuel Adorni on Medium</title>
            <link>https://medium.com/@samuel.adorni?source=rss-7d0485151701------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 00:06:59 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@samuel.adorni/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[Where Async Code Runs in Swift 6.2: nonisolated(nonsending), @concurrent, Sendable and Actors]]></title>
            <link>https://medium.com/@samuel.adorni/where-async-code-runs-in-swift-6-2-nonisolated-nonsending-concurrent-sendable-and-actors-f21f7c2c2f78?source=rss-7d0485151701------2</link>
            <guid isPermaLink="false">https://medium.com/p/f21f7c2c2f78</guid>
            <dc:creator><![CDATA[Samuel Adorni]]></dc:creator>
            <pubDate>Wed, 25 Nov 2026 11:36:27 GMT</pubDate>
            <atom:updated>2026-11-25T11:36:27.403Z</atom:updated>
            <content:encoded><![CDATA[<p><em>You can use this function on either the main thread or in the background; the choice depends on the setting you select during setup. Let’s consider this carefully and make an intentional choice rather than simply letting things happen.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GevS40bgnZb17hkIzR3w4g.png" /></figure><p>We once assumed that any function independent of a particular part of the program and capable of running on its own would always execute in the background. However, Swift 6.2 was released and changed this behavior. Now, the same code may run on the main part of the program, depending entirely on a build-process setting you may not even be aware of. This change occurred with little attention, so you may have overlooked it. Still, you should understand it because it can affect how your code behaves.</p><p>While building a small SwiftUI app, I encountered something interesting. It included a section that retrieves data from a JSON file and transforms it into a list of countries.</p><pre>struct CountryRepository {<br>    let dataSource: any DataSource<br>    func getCountries() async throws -&gt; [Country] {<br>        let data = try await dataSource.fetchData()<br>        return try JSONDecoder().decode([Country].self, from: data)<br>    }<br>}</pre><p>I was working with a ViewModel annotated with @MainActor, meaning that it should execute on the main thread. However, I had some tasks involving file reading and JSON decoding, which are quite CPU-intensive and could slow down the main thread. To prevent this, I wanted to ensure that these tasks did not execute on the main thread. I therefore added a breakpoint in the getCountries() function and used po Thread.current in the console to check which thread was executing it. The result showed that it was running on thread 2, a background thread—exactly what I needed. However, I then enabled Approachable Concurrency and ran the code again. This time, checking the thread showed that it was thread 1, which is the main thread. This was unexpected because the code had not changed, yet it was now running on a different thread. It made me wonder—what is happening with these threads? I thought I understood how they worked, but this caught me by surprise. It turns out that Approachable Concurrency can influence thread usage, even when the code appears unchanged.</p><p>This article compares Swift 5, Swift 6, and the new Swift 6.2. It shows how @concurrent makes things simpler. We&#39;ll also examine why Sendable appears when you use it and when choosing an actor is more appropriate.</p><h3>Before Swift 6.2: “nonisolated async” meant background</h3><p>In Swift 5.7, a new rule was introduced through SE-0338. According to this rule, an async function that is not isolated does not run on the actor’s executor; instead, it uses the global concurrent executor, which functions like a pool of background threads available to anyone. For instance, my getCountries() function is not associated with a specific actor, so when the main actor ViewModel waits for it, the work runs on another thread before the result returns to the main thread. This keeps the main thread from being blocked while the work completes, allowing it to continue handling other tasks.</p><p>My first breakpoint paused a thread that was running in the background. This project used Swift 5 and was configured as nonisolated, so the SE-0338 rule took effect.</p><p>So, let’s be clear about one thing: people often confuse two things that are actually quite different.</p><ul><li>When you write code, the compiler analyzes it in different ways based on the language mode you choose. In Swift 5, you have several options: Minimal, Targeted, or Complete, and if the compiler detects any issues, it will only warn you about them. Swift 6, however, is stricter: it always performs all checks, and any data-race problems it detects are treated as errors rather than warnings. This means you’ll need to resolve those problems before proceeding.</li><li>So, the specific location where a function executes is a separate issue. Merely switching to Swift 6 mode isn’t enough — even with a basic Swift 6 target, nonisolated async functions still execute on the global executor. The important change comes from a specific feature that we’ll cover next.</li></ul><p>The SE-0338 rule was useful because it kept you from blocking the main thread while waiting for a non-isolated function. However, it also had limitations, particularly when dealing with types that aren’t Sendable. For example, if you attempted to call an async method on a non-Sendable object from the main actor, you would need to pass that object to another thread, which Swift 6 mode does not permit. This created problems for many developers adopting strict concurrency, forcing them to find workarounds for the limitation. Many people encountered this issue when trying to use async methods with non-Sendable objects on the main actor.</p><h3>Swift 6.2 has now introduced an update. Now, async functions remain with the entity that called them.</h3><p>Introduced in Swift 6.2, SE-0461 changes the behavior significantly. In essence, a nonisolated async function now uses the same actor as its caller. For example, when called from the main actor, it executes on the main actor. Put simply, that is what nonisolated — or nonsending — actually means.</p><pre>// Runs wherever the caller runs<br>nonisolated(nonsending)<br>func getCountries() async throws -&gt; [Country] {<br>    let data = try await dataSource.fetchData()<br>    return try JSONDecoder().decode([Country].self, from: data)<br>}</pre><p>When working with Xcode, you generally don’t have to enter this setting manually. However, enabling the new feature called NonisolatedNonsendingByDefault makes it the default from that point onward. This feature is actually included in a larger collection of Xcode settings called Approachable Concurrency. Xcode 26 also includes another helpful setting called Default Actor Isolation. It causes every type in your module to use @MainActor unless you explicitly specify otherwise.</p><p>When creating a new project in Xcode 26 or Xcode 27, a couple of features are enabled by default because both versions use the same template. However, an existing project will retain its previous settings unless you decide to update them. At present, this is not the language’s default behavior, but it will change in a future update to the language mode.</p><p>This is where I use my getCountries() function with different settings to observe the results.</p><ul><li>Swift 5 includes a feature called Approachable Concurrency that operates behind the scenes with the global executor. When it is enabled, the compiler checks for issues according to the level you select and reports them as warnings.</li><li>Swift 5 is simplifying concurrency for us. In essence, it executes on the main thread, which acts like the person in charge. The system also performs an additional check and warns us if it detects any issues.</li><li>Swift 6 includes a feature called Approachable Concurrency that works behind the scenes with the global executor. It reviews everything and flags anything it identifies as an error.</li><li>Swift 6 makes things easier with Approachable Concurrency, which runs on the main thread, just like the caller’s actor. It checks everything again, and if anything goes wrong, it considers it an error. This ensures that everything runs smoothly.</li></ul><p>For most coding projects, this update is a positive step forward. It fixes the previous issues that arose in Swift 6 when async methods were used with certain types. Simple apps can now continue running on a single thread unless you choose to use multiple threads. However, there is a catch. Code that previously ran in the background, such as data decoding, will now execute on the main thread. The problem is that you won’t receive any warning or error message — you’ll simply notice that your app’s UI is slower, particularly when handling large files such as JSON. This may create problems, especially when working with large amounts of data.</p><h3>@concurrent: indicate where the work runs</h3><p>SE-0461 identified a workaround for this problem through the use of @concurrent. Adding @concurrent to an async function means it no longer follows the same rules as the code that called it. Instead, it always executes on the global concurrent executor, regardless of the language mode or project configuration in use. As a result, it can run independently without being bound by the same rules as the calling code.</p><pre>struct CountryRepository: Sendable {<br>    let dataSource: any DataSource<br>    @concurrent<br>    func getCountries() async throws -&gt; [Country] {<br>        let data = try await dataSource.fetchData()<br>        return try JSONDecoder().decode([Country].self, from: data)<br>    }<br>}</pre><p>In my project, I discovered that the previous settings had no effect on how tasks executed concurrently. The primary reason is that one function was already running in the background, which is an important detail. At present, decoding does not occur on the main thread; that is simply how the project is configured. However, if someone chooses Approachable Concurrency or sets the default isolation to MainActor, it will begin running on the main thread without any warning. Using @concurrent makes it explicit in the code that this behavior is intentional rather than caused by the project settings. This change transforms something that might happen accidentally into a conscious decision.</p><p>This also applies when your entire project is configured to use the main actor, which is the default in new Xcode 26 projects. When a method is marked with @concurrent, it is removed from the main actor. Therefore, you do not also need to add nonisolated.</p><p>Look more closely instead of simply assuming it is. Set a breakpoint in the function, then enter this in the LLDB console:</p><pre>(lldb) thread info<br>(lldb) po Thread.current</pre><p>On the main thread, the thread info indicates that the queue is listed as &#39;com.apple.main-thread&#39;. When you use Thread.current, you get a result similar to this:</p><pre>&lt;NSMainThread: 0x600001708000&gt;{number = 1, name = main}</pre><p>If you look at the background pool, you will see a basic thread identified only by a number, with no assigned name.</p><pre>&lt;NSThread: 0x10421cb00&gt;{number = 2, name = (null)}</pre><p>Try Approachable Concurrency, execute it both with and without @concurrent, and observe the result. Things begin to make sense once you see thread 1 appear. This is a fairly simple way to understand everything, and it is also surprisingly fast.</p><p>When coding, it is better to use standalone checks instead of depending on threads. In Swift 6, Thread.isMainThread does not work with asynchronous code. The explanation is straightforward: a task may switch threads whenever it waits for something. As a result, tracking which thread is in use becomes difficult.</p><pre>@concurrent<br>func getCountries() async throws -&gt; [Country] {<br>    dispatchPrecondition(condition: .notOnQueue(.main))<br>    // ...<br>}<br>@MainActor<br>func loadCountries() async {<br>    MainActor.assertIsolated()<br>    // ...<br>}</pre><p>Although Task.detached does the job, it is not the ideal approach. The issue is that you need to add it with every call rather than applying it directly to the function. This can be somewhat troublesome. Moreover, when you use Task.detached, it creates a task that doesn&#39;t follow a defined structure—it doesn&#39;t inherit the caller&#39;s cancellation or priority. Therefore, if something happens, such as the screen disappearing, the task continues running, which is less than ideal. By contrast, @concurrent works differently. It is declared in one location, where the actual work takes place, and remains connected to the caller&#39;s task. As a result, you don&#39;t need to add it each time you make a call, and it follows the caller&#39;s structure, making it easier to manage.</p><h3>Why Sendable comes with it</h3><p>Using @concurrent with a function is similar to sending a message to another part of your program. Imagine it as a separate room in which the function runs independently. The problem occurs when you call this function from the main part of your program, since it executes in that separate room. This may create issues because the ViewModel controls the repository while running in the main room. However, the function getCountries() runs in the background, meaning it crosses into a different area. To prevent problems, the information passed between these areas must be handled carefully. Fortunately, Swift 6 includes a feature that helps you do this safely by checking your code and ensuring it is correct.</p><p>I tried it by removing Sendable from the repository and its DataSource protocol, and then switching the target to Swift 6.</p><ul><li>Using @concurrent in the ViewModel can be challenging. It does not work well because it can cause problems when you attempt to send data to the repository simultaneously. This is known as a data race, and it is a problem.</li><li>Without @concurrent, something interesting occurs with Approachable Concurrency: the error disappears. This happens because the function now executes on the same actor as the caller. Consequently, no data has to be exchanged, so it no longer needs to be Sendable. It’s a fairly simple fix.</li><li>Here’s the rewritten paragraph: We have a problem with the line static let bundle = CountryRepository(...). The key point is that a static property acts like a setting accessible to every part of the program. Since many operations may occur simultaneously, Swift 6 includes a rule for dealing with this. You can do this only when the type is safe to share across multiple parts of the program, a property known as being Sendable.</li></ul><p>There’s an issue when you test something. If you run Swift 5 with basic checks, your project may work perfectly well even without using Sendable. The reality is that your code remains insecure; it’s simply that no one is checking for errors.</p><p>Swift can detect Sendable automatically, so why bother writing it explicitly? For internal structs and enums whose properties are all Sendable, Swift determines this automatically. However, this does not apply to protocols, classes, or public types—they always require it to be declared manually. I prefer to declare it explicitly because of where the error message appears. For example, if you add a property that is not Sendable, the error will appear in a particular location.</p><pre>final class Cache {<br>    var countries: [Country] = []<br>}<br>struct CountryRepository: Sendable {<br>    let dataSource: any DataSource<br>    let cache = Cache()   // error here: non-Sendable stored property<br>}</pre><p>When you explicitly indicate that something complies with a rule, the compiler will identify the exact point where the problem occurs. However, if you leave it unclear, the issue may not show up immediately. It can create problems elsewhere, such as in static properties or the ViewModel, forcing you to investigate to determine what is happening. By declaring that a type conforms to a rule, such as Sendable, you are making a commitment that the compiler verifies. And when you declare that a protocol such as DataSource conforms to Sendable, that commitment extends to every data source created afterward. This helps you prevent errors that could arise later.</p><h3>Struct with @concurrent, actor or Task.detached?</h3><p>You may therefore wonder why the repository should not simply be converted into an actor. This allows it to manage things independently without relying on the main thread. Although this approach works, it is more than our repository actually needs. Actors are useful when you need to send them messages and let them process those messages independently, but our repository does not face that type of problem. Using an actor here would be like applying an oversized solution to a minor issue.</p><p>Think of an actor, then, as a watchdog that monitors shared data and prevents multiple operations from accessing it simultaneously. The problem is that my repository does not really contain mutable data; it simply receives information and converts it into a list of countries. The difficulty is that an actor can process only one request at a time, even when several screens are attempting to load data simultaneously. As a result, one screen must wait for the other to finish processing, which does not make much sense. In contrast, using a struct that can be sent concurrently allows multiple screens to load data at the same time without waiting for one another, making it a much better approach.</p><p>When the government becomes involved, the situation changes. If the repository retains the countries it already has, then the actor is correct:</p><pre>actor CountryRepository {<br>    private let dataSource: any DataSource<br>    private var cache: [Country]?<br>    init(dataSource: any DataSource) {<br>        self.dataSource = dataSource<br>    }<br>    func getCountries() async throws -&gt; [Country] {<br>        if let cache { return cache }<br>        let data = try await dataSource.fetchData()<br>        let countries = try JSONDecoder().decode([Country].self, from: data)<br>        cache = countries<br>        return countries<br>    }<br>}</pre><p>When we use a cache, it isn’t locked, so everyone receives the same value, which is fairly straightforward. However, other tasks can interrupt and begin doing their own work. For instance, if the first task is waiting for something to occur, another task may arrive and start its own fetch if the cache remains empty. This can create problems, so we can avoid them by storing the task that is already running and making subsequent tasks wait for it, much like taking a number and standing in line.</p><p>Comparison:</p><h3>Struct with @concurrent</h3><ul><li>This tool relies on what is known as the global executor. It allows multiple requests to run at the same time. They execute in parallel, meaning they all proceed simultaneously.</li><li>State: none; it must not contain any.</li><li>We need to send something, so it must be a specific type with certain features that we already know about.</li><li>The person using the function cancels it. This information is specified only once, directly in the function.</li><li>For tasks that require substantial computing power, such as image processing or data decoding, use Web Workers. They are well suited to jobs that do not need to track what happens from one moment to the next. This covers tasks such as parsing information.</li></ul><h3>Actor</h3><ul><li>The actor manages its own execution. It handles one call at a time, executing each separately.</li><li>State: protects mutable state without using locks.</li><li>Sendable: nothing additional; actors are Sendable.</li><li>The caller determines when cancellation occurs. This depends on the call type and occurs only once.</li><li>Use it for frequently changing data, such as caches or counters, when many people are using it.</li></ul><h3>Task.detached</h3><ul><li>This operates on a global system that manages tasks. Therefore, if you attempt several things simultaneously, they will all run at the same time, alongside one another.</li><li>State: no safeguards.</li><li>Sendable: every value captured by the closure must be Sendable.</li><li>Cancellation: not inherited. Written at each call site.</li><li>Use it only when truly necessary, such as when creating something that must outlive the operation that created it. It is intended for situations where you want to create something that persists.</li></ul><p>I follow a basic approach: begin with the standard setup and keep asynchronous code connected to whatever is calling it. If a function performs substantial intensive work that cannot be interrupted, I add a concurrent tag. However, I use an actor only when something needs protection, such as shared data accessed by multiple parts of the program.</p><h3>Conclusion</h3><p>“Async” was not actually about threads; it only seemed that way initially. However, with Swift 6.2, things are clearer: when you call an async function, it remains where it is, and moving the work elsewhere requires an explicit request. This approach is more logical. In most cases, code does not need to leave the main area, and when it stays there, it does not need to prove that it is safe to send. This makes things simpler and more efficient. You can focus solely on what needs to be done without worrying about additional steps.</p><p>The old approach is no longer viable. If your project uses non-isolated background functions, it depends on a particular build setting. The issue is that settings may change — for instance, when you begin using a new template in Xcode, move to Swift 6, or someone on your team enables Approachable Concurrency. However, resolving this issue is fairly straightforward. You only need to make a few minor adjustments: mark intensive work as @concurrent, add Sendable when passing values between separate parts, and use actors to protect the state that requires it.</p><p>When I worked on my project, I noticed that using @concurrent did not appear to significantly affect how the program ran. However, it did change how I approach the code: I now consider where each async function is executing and why it is running there. To determine where something is running, I can simply add a breakpoint and inspect Thread.current, which is quite quick. As for why it is running that way, the code itself should make that clear.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f21f7c2c2f78" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Combine and UIKit — how to get modern applications on legacy infrastructure]]></title>
            <link>https://medium.com/@samuel.adorni/combine-and-uikit-how-to-get-modern-applications-on-legacy-infrastructure-a875bdb13a6e?source=rss-7d0485151701------2</link>
            <guid isPermaLink="false">https://medium.com/p/a875bdb13a6e</guid>
            <dc:creator><![CDATA[Samuel Adorni]]></dc:creator>
            <pubDate>Wed, 30 Sep 2026 14:09:16 GMT</pubDate>
            <atom:updated>2026-09-30T14:09:16.858Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-yrLw9dBwaTNssQCLNlmTw.png" /></figure><p>By now it’s clear: native development, and iOS development in particular, is moving in a precise direction, declarative programming. Apple itself has been pointing toward a reactive future for some years now, with the release of new libraries, SwiftUI chief among them.</p><p>As technologies advance, however, it’s natural that some teams, whether by choice or necessity, can’t always keep pace, at least not immediately.</p><p>During my job search, I frequently came across companies looking for iOS developers with experience in frameworks like UIKit and Combine, with SwiftUI knowledge listed as a nice-to-have. How is that possible? Why, in a world constantly racing toward the future, do some companies, paradoxically the mid-to-large ones, need developers whose preferred skillset skews “old” rather than “up to date”?</p><p>It reminds me of something my university professors used to tell us: <em>“COBOL programmers are in huge demand, especially in banking. It’s a language that’s been deprecated for 30 years, but banking systems are just too hard to modernise.”</em> The underlying logic is roughly the same, but to better understand the root of this need, I’d like to offer a brief historical overview, especially for those who are newer to iOS development.</p><p>Apple announced its new mobile device to the world in January 2007. Native development as we know it today didn’t yet exist, in fact, Apple had no plans for third-party native apps at all. There was no App Store, no SDK. That would come more than a year later. <br>In March 2008, Apple released its SDK for native development. Swift didn’t yet officially exist as a language, but UIKit was already available for building modern, powerful views. MVC was Apple’s recommended architecture.<br>Until 2014, Objective-C, a fairly convoluted and unwieldy language, remained the primary language for iOS development, until Swift arrived and revolutionised the entire Apple ecosystem.<br>Building native iOS apps became more accessible, a new generation of iOS developers emerged, and companies began racing to claim their spot on the App Store. It was the app boom.<br>As the market expanded, applications grew increasingly sophisticated and complex. MVC began to show its limitations as a scalable architecture, largely due to the so-called “Massive View Controller” problem.<br>It was at this point that mobile software engineers began migrating toward a new architectural pattern. MVVM and reactive programming started gaining traction, not just in native development, but across the industry (see the rise of frameworks like Angular and React on the web, and Kotlin on Android).</p><p>New frameworks were needed to support a clean transition to this new paradigm. Following the widespread adoption of third-party solutions like RxSwift, Apple released Combine in 2019, the subject of this article. Alongside it came a new UI library built around reactivity as its core principle: SwiftUI, the present and future of iOS development.</p><p>With this timeline in view, the driving force behind the whole discussion becomes clear, and we can finally answer our original questions.</p><p>Companies that have been building native applications since 2008 carry over a decade of UIKit development, projects with potentially hundreds of views and view controllers, all working seamlessly together. Migrating to SwiftUI is possible, but it’s a significant undertaking.</p><p>That’s why many companies with what I’ve called “legacy” infrastructure, built on UIKit, need to maintain projects using that UI library while still gaining the benefits of an MVVM architecture. Combine, in this context, becomes the keystone of the entire system: the variable that solves the equation. And that’s exactly why we’re here.</p><p><strong>MVC vs MVVM — what makes one better than the other?</strong></p><p>The web is full of guides, courses, tutorials and documents comparing MVC and MVVM. If you have ever developed for native iOS, you have almost certainly encountered these architectural patterns, whether consciously or not.</p><p>For the purposes of our discussion, though, it is important to have a clear picture of what differentiates one pattern from the other, so bear with me while I run through a brief theoretical recap. Reviewing the basics never hurts, repetita iuvant 🙃</p><p>MVC (literally Model-View-Controller) did not originate with UIKit or Apple in general; its roots go back much further. What we can say is that the entire UIKit library was designed to adhere to this type of architecture.</p><p>In MVC, the two fundamental entities that govern how the software operates are:</p><ul><li><strong>The Model:</strong> responsible for representing the data that will be handled within the application.</li><li><strong>The Controller:</strong> contains the views and everything needed to manage them.</li></ul><p>With MVC, the decision is made to explicitly centralise data management on one side and user interaction on the other, inside a single large object: the controller. Any given controller ends up containing:</p><ul><li>UI logic</li><li>networking</li><li>validation</li><li>coordination</li><li>state management</li></ul><p>When applications are simple and their logic is not too complex (as was often the case in the early days of native development), MVC is the easiest architecture to understand and the most straightforward to develop with.</p><p>It quickly becomes clear, however, that as the application and its controllers grow, this kind of management soon becomes an obstacle, bringing with it confusion and files of unwieldy size.</p><p>With MVVM (literally Model-View-ViewModel), everything becomes more modular and more easily scalable.</p><p>At the core of this pattern is a complete and clean separation between the views and the business logic. Where MVC bundled everything into one large object, MVVM introduces the view model, making it possible to separate what is displayed from what is computed.</p><ul><li><strong>The Model:</strong> conceptually the same as in MVC, its job is to represent the data that will be handled within the application.</li><li><strong>The View:</strong> a standalone object that contains only the views. Its job is to display data to the user and capture their interactions. It is crucial that the view applies no logic whatsoever. The common saying is that “the view must be dumb”: it should act purely as an intermediary between the user and the view model, meaning it only displays the data provided by the view model and notifies the view model when the user performs an action. Nothing more, nothing less.</li><li><strong>The ViewModel:</strong> this is where all computational and logical responsibility lives. If data needs to be fetched, it manages the interaction with networking objects. If raw data needs to be aggregated in some way, it handles the mapping. If the app’s behaviour needs to maintain a certain data consistency, it handles the validation. It is the brain of the software; the views are the hands.</li></ul><p><strong>Let’s have some fun-coding</strong></p><p>Until you actually get your hands on the code, it is hard to truly understand what we are trying to achieve, so in the sections that follow I will walk through an MVC code example of a very simple application, one that is basic enough to be illustrative for our purposes.</p><p>The goal of the app is to display a list of users and their respective email addresses. These users can be filtered by name. There is a button that is only enabled if the list contains at least one user, meaning at least one user has been loaded and the current filter has returned a non-empty list.</p><pre>struct User: Decodable {<br>    let id: Int<br>    let name: String<br>    let email: String<br>}</pre><p>I am placing the model above everything else, since, as we saw earlier, it is the only structure that remains unchanged between MVC and MVVM.</p><pre> <br>// A very simple networking layer, reused as it is in the next examples<br>final class UserService {<br>    func fetchUsers(completion: @escaping (Result&lt;[User], Error&gt;) -&gt; Void) {<br>        let url = URL(string: &quot;https://api.example.com/users&quot;)!<br>        URLSession.shared.dataTask(with: url) { data, _, error in<br>            if let error {<br>                completion(.failure(error))<br>                return<br>            }<br>            do {<br>                let users = try JSONDecoder().decode([User].self, from: data ?? Data())<br>                completion(.success(users))<br>            } catch {<br>                completion(.failure(error))<br>            }<br>        }.resume()<br>    }<br>}<br>final class UsersViewController: UIViewController, UITableViewDataSource {<br>    // MARK: - Views<br>    private let searchField = UITextField()<br>    private let tableView = UITableView()<br>    private let exportButton = UIButton(type: .system)<br>    // MARK: - Data<br>    private let service = UserService()<br>    private var allUsers: [User] = []<br>    private var filteredUsers: [User] = []<br>    // MARK: - Lifecycle<br>    override func viewDidLoad() {<br>        super.viewDidLoad()<br>        setupViews()<br>        loadUsers()<br>    }<br>    // MARK: - UI setup<br>    private func setupViews() {<br>        view.backgroundColor = .systemBackground<br>        searchField.placeholder = &quot;Search by name&quot;<br>        searchField.addTarget(self, action: #selector(searchTextChanged), for: .editingChanged)<br>        tableView.dataSource = self<br>        tableView.register(UITableViewCell.self, forCellReuseIdentifier: &quot;UserCell&quot;)<br>        exportButton.setTitle(&quot;Export&quot;, for: .normal)<br>        exportButton.isEnabled = false<br>        exportButton.addTarget(self, action: #selector(exportTapped), for: .touchUpInside)<br>        // ...add subviews and Auto Layout constraints<br>    }<br>    // MARK: - Networking<br>    private func loadUsers() {<br>        service.fetchUsers { [weak self] result in<br>            DispatchQueue.main.async {<br>                guard let self else { return }<br>                switch result {<br>                case .success(let users):<br>                    self.allUsers = users<br>                    self.applyFilter(self.searchField.text ?? &quot;&quot;)<br>                case .failure(let error):<br>                    self.showError(error.localizedDescription)<br>                }<br>            }<br>        }<br>    }<br>    // MARK: - Filtering<br>    @objc private func searchTextChanged() {<br>        applyFilter(searchField.text ?? &quot;&quot;)<br>    }<br>    private func applyFilter(_ text: String) {<br>        filteredUsers = text.isEmpty<br>            ? allUsers<br>            : allUsers.filter { $0.name.localizedCaseInsensitiveContains(text) }<br>        tableView.reloadData()<br>        updateExportButton()<br>    }<br>    // MARK: - Validation<br>    private func updateExportButton() {<br>        exportButton.isEnabled = !allUsers.isEmpty &amp;&amp; !filteredUsers.isEmpty<br>    }<br>    // MARK: - Actions<br>    @objc private func exportTapped() {<br>        print(&quot;Exporting \(filteredUsers.count) users&quot;)<br>    }<br>    private func showError(_ message: String) {<br>        let alert = UIAlertController(title: &quot;Error&quot;, message: message, preferredStyle: .alert)<br>        alert.addAction(UIAlertAction(title: &quot;OK&quot;, style: .default))<br>        present(alert, animated: true)<br>    }<br>    // MARK: - UITableViewDataSource<br>    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -&gt; Int {<br>        filteredUsers.count<br>    }<br>    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -&gt; UITableViewCell {<br>        let cell = tableView.dequeueReusableCell(withIdentifier: &quot;UserCell&quot;, for: indexPath)<br>        let user = filteredUsers[indexPath.row]<br>        var content = cell.defaultContentConfiguration()<br>        content.text = user.name<br>        content.secondaryText = user.email<br>        cell.contentConfiguration = content<br>        return cell<br>    }<br>}</pre><p>It should now be clear exactly what we meant earlier by “Massive View Controller”. The project is stripped down to its bare bones here, but take a moment to imagine what could happen if more views were added to this view controller, each needing to interact with the others.</p><p>Let’s move toward a more modern solution, oriented around MVVM. For the more impatient readers, I have some bad news: for now, we are going to pretend that Combine does not exist and that we have no idea what it is. I know that if you have made it this far, you will be able to accept this part of the journey. My goal is to make it as gradual and clear as possible, so enjoy this intermediate step 😉</p><pre>protocol UsersViewModelDelegate: AnyObject {<br>    func usersViewModelDidUpdateUsers(_ viewModel: UsersViewModel)<br>    func usersViewModel(_ viewModel: UsersViewModel, didChangeExportEnabled isEnabled: Bool)<br>    func usersViewModel(_ viewModel: UsersViewModel, didFailWith message: String)<br>}<br>final class UsersViewModel {<br>    weak var delegate: UsersViewModelDelegate?<br>    private let service: UserService<br>    private var allUsers: [User] = []<br>    private(set) var filteredUsers: [User] = []<br>    init(service: UserService = UserService()) {<br>        self.service = service<br>    }<br>    func loadUsers() {<br>        service.fetchUsers { [weak self] result in<br>            DispatchQueue.main.async {<br>                guard let self else { return }<br>                switch result {<br>                case .success(let users):<br>                    self.allUsers = users<br>                    self.filter(by: &quot;&quot;)<br>                case .failure(let error):<br>                    self.delegate?.usersViewModel(self, didFailWith: error.localizedDescription)<br>                }<br>            }<br>        }<br>    }<br>    func filter(by text: String) {<br>        filteredUsers = text.isEmpty<br>            ? allUsers<br>            : allUsers.filter { $0.name.localizedCaseInsensitiveContains(text) }<br>        delegate?.usersViewModelDidUpdateUsers(self)<br>        delegate?.usersViewModel(self, didChangeExportEnabled: !allUsers.isEmpty &amp;&amp; !filteredUsers.isEmpty)<br>    }<br>    func exportUsers() {<br>        print(&quot;Exporting \(filteredUsers.count) users&quot;)<br>    }<br>}<br>// MARK: - View<br>final class UsersViewController: UIViewController, UITableViewDataSource, UsersViewModelDelegate {<br>    private let viewModel: UsersViewModel<br>    private let searchField = UITextField()<br>    private let tableView = UITableView()<br>    private let exportButton = UIButton(type: .system)<br>    init(viewModel: UsersViewModel) {<br>        self.viewModel = viewModel<br>        super.init(nibName: nil, bundle: nil)<br>    }<br>    required init?(coder: NSCoder) {<br>        fatalError(&quot;init(coder:) has not been implemented&quot;)<br>    }<br>    override func viewDidLoad() {<br>        super.viewDidLoad()<br>        setupViews() // same as the MVC version<br>        viewModel.delegate = self<br>        viewModel.loadUsers()<br>    }<br>    // MARK: - View -&gt; ViewModel<br>    @objc private func searchTextChanged() {<br>        viewModel.filter(by: searchField.text ?? &quot;&quot;)<br>    }<br>    @objc private func exportTapped() {<br>        viewModel.exportUsers()<br>    }<br>    // MARK: - ViewModel -&gt; View (UsersViewModelDelegate)<br>    func usersViewModelDidUpdateUsers(_ viewModel: UsersViewModel) {<br>        tableView.reloadData()<br>    }<br>    func usersViewModel(_ viewModel: UsersViewModel, didChangeExportEnabled isEnabled: Bool) {<br>        exportButton.isEnabled = isEnabled<br>    }<br>    func usersViewModel(_ viewModel: UsersViewModel, didFailWith message: String) {<br>        showError(message) // same as the MVC version<br>    }<br>    // MARK: - UITableViewDataSource<br>    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -&gt; Int {<br>        viewModel.filteredUsers.count<br>    }<br>    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -&gt; UITableViewCell {<br>        let cell = tableView.dequeueReusableCell(withIdentifier: &quot;UserCell&quot;, for: indexPath)<br>        let user = viewModel.filteredUsers[indexPath.row]<br>        var content = cell.defaultContentConfiguration()<br>        content.text = user.name<br>        content.secondaryText = user.email<br>        cell.contentConfiguration = content<br>        return cell<br>    }<br>}</pre><p>It might seem like very little has changed, but if you ever needed to revisit the data logic or add a new view with its own interactions, the process would be significantly easier and faster than having everything nested inside the view controller. I also want to highlight the fact that, if you wanted to, you could keep the same view and swap in two different view models. This means you could change the underlying logic without having to redesign or duplicate any code.</p><p>Equally, if you decided one day to change the visual appearance of the application, you could simply update or create a new view, leaving the view model completely untouched.</p><p>This structure, especially in this more “primitive” form, does come with some limitations. One obstacle common to all older iOS code is delegate management. In order to allow the view model and the view to communicate, you need to create a protocol that exposes completion callbacks to be executed when the view model reaches certain points in its data processing flow. The more callbacks you need from the view to update the data, the more functions you end up adding to the protocol. What you gain in modularity, you risk losing in readability and maintainability.</p><p>And this is where the true protagonist of our series comes in: Combine.</p><p><strong>Combine: why it is so important?</strong></p><p>We have arrived at Combine by following a very deliberate path. It might almost seem as though Combine was designed specifically to address problems like the ones we described, but that is not entirely the case. Combine was born out of the need to create flows of synchronous, and in particular asynchronous, operations to be applied to data.</p><p>I know that phrased that way it sounds like the most abstract explanation in the world, which is exactly why I would like to go back to our users app to get to the heart of the matter.<br>So far, our list is downloaded once and filtered locally, on the device. In a real product, though, requirements tend to grow quickly: the users live on a server, there are thousands of them, and the search by name has to be performed by the API. As soon as this happens, a small chain of rules appears almost by itself:</p><p>USER TYPES IN THE SEARCH FIELD <br>⬇ <br>WAIT UNTIL THE USER STOPS TYPING <br>⬇ <br>SKIP THE SEARCH IF THE TEXT HAS NOT CHANGED <br>⬇ <br>CALL THE API, DISCARDING ANY OLDER SEARCH <br>⬇ <br>UPDATE LIST AND BUTTON ON THE MAIN THREAD</p><p>No stage of this chain has a fixed duration. The user might stop typing after half a second or after ten, and the API might answer in a hundred milliseconds or in five seconds, possibly when the user has already typed something else. Still, I want each stage to start as soon as the previous one has finished, and I want the screen to always show the results of the last thing the user typed, never those of an older search.<br>If we were to add these rules to the view model we have just written, in terms of “old school Swift”, the code would look something like this:</p><pre>// UserService<br>// func search(query: String, completion: @escaping ([User]) -&gt; Void) {<br>//      calls the API<br>// }<br><br>final class UsersViewModel {<br><br>    weak var delegate: UsersViewModelDelegate?<br><br>    private let service: UserService<br>    private(set) var users: [User] = []<br><br>    private var debounceTimer: Timer?<br>    private var lastQuery: String?<br>    private var latestRequestID = UUID()<br><br>    init(service: UserService = UserService()) {<br>        self.service = service<br>    }<br><br>    deinit {<br>        debounceTimer?.invalidate()<br>    }<br><br>    // Called by the view controller on every keystroke<br>    func searchTextChanged(_ text: String) {<br>        // 1. wait until the user stops typing<br>        debounceTimer?.invalidate()<br>        debounceTimer = Timer.scheduledTimer(withTimeInterval: 0.3, repeats: false) { [weak self] _ in<br>            self?.performSearch(text)<br>        }<br>    }<br><br>    private func performSearch(_ text: String) {<br>        // 2. skip the search if the text has not changed<br>        guard text != lastQuery else { return }<br>        lastQuery = text<br><br>        // 3. remember which one is the latest request<br>        let requestID = UUID()<br>        latestRequestID = requestID<br><br>        service.search(query: text) { [weak self] users in<br>            // 4. go back to the main thread<br>            DispatchQueue.main.async {<br>                guard let self else { return }<br>                // 5. discard the responses of older searches<br>                guard requestID == self.latestRequestID else { return }<br><br>                self.users = users<br>                self.delegate?.usersViewModelDidUpdateUsers(self)<br>                self.delegate?.usersViewModel(self, didChangeExportEnabled: !users.isEmpty)<br>            }<br>        }<br>    }<br>}</pre><p>And we have not even handled error propagation yet, even though, in cases like this, the chance that one of the operations might fail is very common. So let’s add error handling, a couple of automatic retries for temporary network issues and, since the button must stay disabled while a search is still running, a loading state as well.</p><pre>// UserService<br>// func search(query: String, completion: <br>//                    @escaping (Result&lt;[User], Error&gt;) -&gt; Void) {<br>//     calls the API and report failure too<br>// }<br><br>final class UsersViewModel {<br><br>    weak var delegate: UsersViewModelDelegate?<br><br>    private let service: UserService<br>    private(set) var users: [User] = []<br><br>    private var debounceTimer: Timer?<br>    private var lastQuery: String?<br>    private var latestRequestID = UUID()<br>    private var isLoading = false<br>    private let maxAttempts = 3<br><br>    init(service: UserService = UserService()) {<br>        self.service = service<br>    }<br><br>    deinit {<br>        debounceTimer?.invalidate()<br>    }<br><br>    func searchTextChanged(_ text: String) {<br>        debounceTimer?.invalidate()<br>        debounceTimer = Timer.scheduledTimer(withTimeInterval: 0.3, repeats: false) { [weak self] _ in<br>            self?.performSearch(text)<br>        }<br>    }<br><br>    private func performSearch(_ text: String) {<br>        guard text != lastQuery else { return }<br>        lastQuery = text<br><br>        let requestID = UUID()<br>        latestRequestID = requestID<br><br>        isLoading = true<br>        notifyExportState()<br><br>        search(text, requestID: requestID, attempt: 1)<br>    }<br><br>    private func search(_ text: String, requestID: UUID, attempt: Int) {<br>        service.search(query: text) { [weak self] result in<br>            DispatchQueue.main.async {<br>                guard let self else { return }<br>                guard requestID == self.latestRequestID else { return }<br><br>                switch result {<br>                case .success(let users):<br>                    self.isLoading = false<br>                    self.users = users<br>                    self.delegate?.usersViewModelDidUpdateUsers(self)<br>                    self.notifyExportState()<br><br>                case .failure(let error):<br>                    if attempt &lt; self.maxAttempts {<br>                        // try again, keeping the same request identifier<br>                        self.search(text, requestID: requestID, attempt: attempt + 1)<br>                    } else {<br>                        self.isLoading = false<br>                        self.users = []<br>                        self.lastQuery = nil // otherwise the same text could never be searched again<br>                        self.delegate?.usersViewModelDidUpdateUsers(self)<br>                        self.delegate?.usersViewModel(self, didFailWith: error.localizedDescription)<br>                        self.notifyExportState()<br>                    }<br>                }<br>            }<br>        }<br>    }<br><br>    private func notifyExportState() {<br>        let isEnabled = !isLoading &amp;&amp; !users.isEmpty<br>        delegate?.usersViewModel(self, didChangeExportEnabled: isEnabled)<br>    }<br>}</pre><p>Looking at this as a beginner, my only thought would be: “if there is no solution to this problem, I probably do not want to become an iOS developer anymore.”</p><p>This way of thinking feels a bit convoluted to us because our minds work sequentially. Just as I represented the flow structure with arrows, our brain is used to reasoning in a linear, step-by-step way. It would therefore be much more convenient to have a construct capable of executing the same logic with a similar style of writing.</p><p>Let’s take a closer look at what we actually wrote. Almost none of it is business logic: it is plumbing. A Timer to wait for the user, a variable to remember the last query, an identifier to throw away outdated responses, a counter for the retries, a manual jump back to the main thread, a flag to keep the button consistent and a delegate protocol that grows every time the view needs to know something new. On top of that, all these pieces are scattered across different methods and properties, so the flow we described with the arrows can only be reconstructed by jumping back and forth through the file.<br>Now the good news: each of these hand-written pieces has a ready-made counterpart in Combine, and we are going to meet all of them in the next section:<br> • the Timer becomes debounce<br> • lastQuery becomes removeDuplicates<br> • the request identifier becomes switchToLatest<br> • the attempt counter becomes retry<br> • the switch on the Result becomes catch (or replaceError)<br> • DispatchQueue.main.async becomes receive(on:)<br> • the loading flag and the button state become a combineLatest<br> • the old completion-based search becomes a Future<br> • the delegate protocol becomes a few publishers exposed by the view model, kept clean by eraseToAnyPublisher() and kept alive by store(in:)<br>And, most importantly, with Combine these pieces are written one after the other, in the same order in which we reason about them. This is why, if you want to use MVVM in a UIKit project, Combine is worth learning: almost every concept in the next chapter is a building block that we will use, at the end of this article, to rebuild this very screen. Keep this list in mind while reading the theory.</p><p>And this is exactly where our new framework, Combine, comes into play.</p><p>At a theoretical level, Combine is a chain of objects that emit a value and wait for a value. More specifically, we call Publishers the elements that emit (publish) a value, and Subscribers the elements that wait for a value (subscribing to it). At the start of the chain there must always be a Publisher, at the end a Subscriber, and in between there are objects that act as both, receiving a value and re-emitting it.</p><p>Below are the main Combine operators and their roles within a pipeline.</p><p><strong>Core Publishers and State Management in Combine</strong></p><p>Before discussing Combine operators, it is important to understand the main types used to create and manage data streams within an application. In particular, PassthroughSubject, CurrentValueSubject, @Published, ObservableObject, and Future represent the foundation upon which most Combine-based architectures are built.</p><p>These components are closely related and are frequently used together to propagate state changes, manage user interactions, perform asynchronous operations, and automatically update the user interface.</p><p><strong>Subjects in Combine</strong></p><p>A Subject is a special type of Publisher that can both publish values and receive values. Unlike publishers such as Just or URLSession.DataTaskPublisher, which generate values automatically, Subjects allow developers to manually inject values into a stream.</p><p>Combine provides two main Subject implementations:<br>PassthroughSubject andCurrentValueSubject</p><p>Although they appear similar, they are designed for different use cases.</p><p><strong>PassthroughSubject</strong></p><p>A PassthroughSubject broadcasts values to its subscribers as they are received. It does not store any value internally.</p><p>If a subscriber is attached after a value has already been emitted, that value is lost and will not be delivered to the new subscriber.</p><p>PassthroughSubject is commonly used to model events rather than state.</p><p>Examples include:</p><ul><li>Button taps</li><li>User interactions</li><li>Notifications</li><li>Navigation events</li><li>Temporary messages</li></ul><p>For example, a button press can be represented as follows:</p><pre>let loginTapped = PassthroughSubject&lt;Void, Never&gt;()<br><br>loginTapped<br>    .sink {<br>        print(&quot;😀 Button tapped from the view model&quot;)<br>    }</pre><p>In this scenario, the event is relevant only at the moment it occurs and does not need to be stored.</p><p>If I have a button and I configure to send a signal to this previous Publisher, when the button is clicked I will print in output those string</p><pre>// IN VIEW CONTROLLER<br>...<br>let button = UIButton()<br>button..addTarget(self, action: #selector(buttonClick), for: .touchUpInside)<br>...<br><br>@objc func buttonClick() {<br>    viewModel.loginTapped.send()<br>}<br><br>// OUTPUT:<br>// 😀 Button tapped from the view model</pre><p>We are going to analyze <em>sink </em>operator in detail later in this<em> </em>document. So by now it’s important to understand that <em>sink</em> intercept a change in the publisher and when this change is emitted the code inside the sink will be executed</p><p><strong>CurrentValueSubject</strong></p><p>A CurrentValueSubject behaves similarly to a PassthroughSubject, but it always stores the latest value it has received.</p><p>Whenever a new subscriber attaches, it immediately receives the current value.</p><p><strong>Typical Use Cases</strong></p><p>CurrentValueSubject is ideal for representing application state.</p><ul><li>Current user information</li><li>Authentication state</li><li>Theme settings</li><li>Application preferences</li><li>Current screen state</li></ul><p><strong>Passthrough or CurrentValue?</strong></p><p>Well, when you are coding and you have to decide which of those two subject you should use, you have to ask yourself this question:</p><blockquote>Am I modeling a transient event that should only be observed at the moment it occurs, or a persistent state that has a meaningful current value which must always be available to any new subscriber?</blockquote><p>Let’s compare these two behaviours and let’s try to have the sharpest view about this topic</p><p><em>&gt;&gt;PassthroughSubject&lt;&lt;</em></p><pre>let subject = PassthroughSubject&lt;String, Never&gt;()<br><br>subject.send(&quot;Hello&quot;)<br><br>subject<br>    .sink { value in<br>        print(value)<br>    }<br><br>// NO OUTPUT AT THIS TIME<br><br>subject.send(&quot;World&quot;)<br><br>// Output:<br>// World</pre><p>“Hello” string is not emitted because it is send before the subscription to that Publisher</p><p><em>&gt;&gt;CurrentValueSubject&lt;&lt;</em></p><pre>let username = CurrentValueSubject&lt;String, Never&gt;(&quot;Guest&quot;)<br><br>username<br>    .sink { value in<br>        print(value)<br>    }<br><br>// Output:<br>// Guest<br><br>username.send(&quot;Mario&quot;)<br><br>// Output:<br>// Mario</pre><p>When the sink subscriber is attached to username publisher it already has a value, so it emits immediately. And It emits also when it has been modified of course.</p><p>So that’s clear that CurrentValueSubject is perfect to store a state and the PassthroughSubject is design to only intercept an event without storing some data.</p><p><strong>Honorable mention: @Publised and ObservableObject</strong></p><p>In projects based purely on UIKit, @Published and ObservableObject are not strictly necessary for the scope of this study, as they are primarily designed for SwiftUI-based architectures and declarative UI state management. However, a brief mention is useful to understand how Combine integrates with modern Apple frameworks.</p><p>In SwiftUI, CurrentValueSubject is often conceptually replaced by @Published, which provides a more native and declarative way to expose state changes. @Published automatically creates a publisher that emits updates whenever a property changes, making it the preferred mechanism for state propagation in SwiftUI-based architectures.</p><p>ObservableObject is used as the base class for reference-type view models that need to be observed by SwiftUI views. Since SwiftUI views are value types (struct) and are frequently recreated by the framework, ObservableObject ensures that the underlying state is not recreated with each view refresh. Instead, the same instance is retained and observed, allowing the UI to remain consistent while only reacting to changes in the published properties.</p><p><strong>Future</strong></p><p>A Future is a Publisher designed to represent an asynchronous operation that produces a single result or a single error.</p><p>Unlike many publishers that can emit multiple values over time, a Future completes after emitting exactly one value.</p><p><strong>Typical Use Cases</strong></p><p>A Future is commonly used to model:</p><ul><li>Network requests</li><li>Authentication operations</li><li>File loading</li><li>Database queries</li><li>Long-running asynchronous computations</li></ul><p>In UIKit-based architectures, Future is not strictly required for the core reactive model of Combine, but it becomes particularly useful when dealing with legacy asynchronous code based on completion handlers. In many real-world projects, Future is often introduced as a bridge mechanism to progressively modernize older APIs without rewriting the entire networking or persistence layer.</p><p>A Future allows a completion-handler-based function to be “wrapped” into a Combine publisher, effectively <em>cleaning up</em> legacy code by transforming callback-based logic into a declarative stream.</p><p>For example, consider a traditional API using a completion handler:</p><pre>func fetchImage(withID id: String, completion: @escaping (Result&lt;Image, Error&gt;) -&gt; Void) {<br>    networkClient.requestImage(id) { result in<br>        completion(result)<br>    }<br>}</pre><p>This can be “modernized” using Future:</p><pre>func fetchImage(withID id: String) -&gt; Future&lt;Image, Error&gt; {<br>    return Future { promise in<br>        networkClient.requestImage(id) { result in<br>            promise(result)<br>        }<br>    }<br>}</pre><p>In this way, the asynchronous operation is encapsulated inside a Combine publisher, making it composable with operators that we will see right away on this thread.</p><p><strong>Deferred: making a Future lazy</strong></p><p>There is one detail of Future that is easy to overlook and that can cause subtle bugs: a Future is eager. Most publishers do nothing until a subscriber attaches to them (we will see this in detail when we talk about sink), but a Future starts its work immediately, as soon as it is created, whether or not anyone is listening. Once the work is done, the result is stored, and every subscriber receives that same stored result.</p><pre>let future = Future&lt;Int, Never&gt; { promise in<br>    print(&quot;Request started&quot;)<br>    promise(.success(42))<br>}<br>// Output:<br>// Request started<br><br>future.sink { print($0) }<br>// Output:<br>// 42<br>future.sink { print($0) }<br>// Output:<br>// 42</pre><p>“Request started” is printed only once, at creation time, before any subscription. The second subscriber does not start a new request: it simply receives the value that was already computed.</p><p>In many cases this is exactly what we want. But if the Future wraps a network call, subscribing to it again will never repeat that call.</p><p>Combine provides Deferred to solve this. Deferred wraps the creation of a publisher and postpones it until the moment a subscriber attaches. Every new subscription creates a brand new Future, and therefore starts the work again.</p><pre>let deferred = Deferred {<br>    Future&lt;Int, Never&gt; { promise in<br>        print(&quot;Request started&quot;)<br>        promise(.success(42))<br>    }<br>}<br>// NO OUTPUT AT THIS TIME<br><br>deferred.sink { print($0) }<br>// Output:<br>// Request started<br>// 42<br>deferred.sink { print($0) }<br>// Output:<br>// Request started<br>// 42</pre><p>Now nothing happens at creation time, and each subscriber triggers its own request.</p><p>Our fetchImage function can be written in the same way:</p><pre>func fetchImage(withID id: String) -&gt; Deferred&lt;Future&lt;Image, Error&gt;&gt; {<br>    Deferred {<br>        Future { promise in<br>            networkClient.requestImage(id) { result in<br>                promise(result)<br>            }<br>        }<br>    }<br>}</pre><p>When does this really matter? The most common case is retrying a failed operation. Later in this document we will see the retry operator, which reacts to an error by subscribing again to the publisher above it. With a plain Future, subscribing again only returns the same stored error, so the request is never actually repeated: the code compiles, nothing crashes, but the retry silently does nothing. Wrapping the Future in Deferred makes every retry a real new attempt.</p><p>On the other hand, Deferred is not always necessary. If a Future is created right when it is needed and subscribed to only once, like inside the flatMap example we will see shortly, where a new Future is created for each emitted ID, its eager behaviour causes no problems.</p><p>A practical rule: whenever a Future wraps work that may need to be started more than once, wrap it in Deferred.</p><p><strong>The sink Subscriber</strong></p><p>Before looking at Combine’s operators, it is important to understand the role of the sink subscriber, one of the most commonly used elements in the framework.</p><p>In Combine, a Publisher does not perform any operation until a Subscriber subscribes to it. This behaviour is known as lazy execution: the pipeline is built but remains inactive until something explicitly requests the data it produces.</p><p>The <strong><em>sink</em></strong> operator is the simplest Subscriber provided by the framework. Its job is to receive the values emitted by a Publisher and optionally handle the completion of the sequence.</p><pre>publisher<br>.sink( <br>  receiveCompletion: <br>    { completion in <br>      switch completion { <br>          case .finished: print(&quot;Finished&quot;) <br>          case .failure(let error): print(&quot;Error: \(error)&quot;) <br>      } <br>    }, <br>  receiveValue: <br>    { users in print(users) } )</pre><p><strong>Subscription Management</strong></p><p>One of the most important concepts in Combine is subscription lifecycle management. Every time a subscriber is attached to a publisher using methods such as <em>sink</em>, Combine returns an object conforming to AnyCancellable.</p><pre>let cancellable = publisher<br>    .sink { value in<br>        print(value)<br>    }</pre><p>An AnyCancellable represents the active subscription between the publisher and the subscriber. If this object is deallocated, the subscription is automatically cancelled and no further values are delivered.</p><p>For this reason, subscriptions are commonly stored inside a collection of AnyCancellable instances:</p><p>The <strong><em>store(in:)</em></strong> method provides a convenient way to retain subscriptions for as long as they are needed:</p><pre>private var cancellables = Set&lt;AnyCancellable&gt;()<br><br>publisher<br>    .sink { value in<br>        print(value)<br>    }<br>    .store(in: &amp;cancellables)</pre><p>Without storing the returned AnyCancellable, the subscription may be released immediately after its creation, causing the publisher to stop delivering values.</p><p>In UIKit applications, <em>store(in:)</em> is typically used inside view controllers, view models, or service objects to keep subscriptions alive for the lifetime of the owning object. When the owner is deallocated, all stored subscriptions are automatically cancelled, preventing memory leaks and unnecessary resource usage.</p><p>Therefore, while <em>store(in:)</em> does not transform the data flowing through a Combine pipeline, it plays a fundamental role in ensuring that subscriptions remain active and behave as expected.</p><p>In next examples in document the <em>store(in:)</em> subscription management will be omitted for readability of the code, but it is important to not forget it while coding!</p><p><strong>Transformation operators</strong></p><p>Transformation operators allow you to modify the values emitted by a Publisher.</p><p>The <strong><em>map</em></strong> operator applies a transformation to each received value, producing a new data stream. It is mainly used to convert models, format strings, or adapt data coming from external services.</p><pre>let publisher = [1, 2, 3].publisher<br><br>publisher<br>    .map { $0 * 2 }<br>    .sink { print($0) }<br><br>//  Output:<br>//  2<br>//  4<br>//  6</pre><p>The <strong><em>compactMap</em></strong> operator serves a similar purpose, but automatically discards any nil values resulting from the transformation. It is particularly useful when parsing optional data.</p><pre>let values = [&quot;1&quot;, &quot;abc&quot;, &quot;3&quot;].publisher<br><br>values<br>    .compactMap { Int($0) }<br>    .sink { print($0) }<br><br>//  Output:<br>//  1<br>//  3</pre><p><strong>Filtering operators</strong></p><p>Filtering operators allow you to select only the values that are relevant to the application.</p><p>The <strong><em>filter</em></strong> operator lets you keep only the elements that satisfy a given logical condition.</p><pre>let publisher = [10, 15, 20, 25].publisher<br><br>publisher<br>    .filter { $0 &gt; 18 }<br>    .sink { print($0) }<br><br>//  Output:<br>//  20<br>//  25</pre><p>The <strong><em>removeDuplicates</em></strong> operator, on the other hand, prevents consecutive identical values from being propagated downstream. This operator is widely used in text field and live search management, avoiding unnecessary processing or network requests.</p><pre>let publisher = [1, 1, 2, 2, 3, 3].publisher<br><br>publisher<br>    .removeDuplicates()<br>    .sink { print($0) }<br>//  Output:<br>//  1<br>//  2<br>//  3</pre><p><strong>Combination operators</strong></p><p>Combine provides several operators for aggregating data streams from different Publishers.</p><p>The <strong><em>merge</em></strong> operator joins multiple Publishers of the same type into a single stream. Values are forwarded as soon as they are received, regardless of their source.</p><pre>let publisherA = [1, 2].publisher<br>let publisherB = [3, 4].publisher<br><br>publisherA<br>    .merge(with: publisherB)<br>    .sink { print($0) }<br><br>//  Possible output if emission order is A-B-B-A:<br>//  1<br>//  3<br>//  4<br>//  2</pre><p>The <strong><em>zip</em></strong> operator combines elements based on their position in the sequence. Each value emitted by one Publisher is paired with the corresponding value from the other.</p><p>It emits only when both of the publishers continue in the sequence.</p><pre>let numbers = [1, 2, 3].publisher<br>let letters = [&quot;A&quot;, &quot;B&quot;, &quot;C&quot;].publisher<br><br>numbers<br>    .zip(letters)<br>    .sink { print($0) }<br><br>//  Output:<br>//  (1, &quot;A&quot;)<br>//  (2, &quot;B&quot;)<br>//  (3, &quot;C&quot;)</pre><p>So there would be never the possibility to have</p><pre>//  Output:<br>//  ...<br>//  (2, &quot;C&quot;)<br>//  ...</pre><p>The <strong><em>combineLatest</em></strong> operator is one of the most widely used in UI development. It produces a new value whenever any of the observed Publishers changes state, always using the latest available value from each stream. This makes it particularly well suited to form validation and the synchronisation of multiple input fields.</p><pre>let numbers = [1, 2, 3].publisher<br>let letters = [&quot;A&quot;, &quot;B&quot;, &quot;C&quot;].publisher<br><br>numbers<br>    .combineLatest(letters)<br>    .sink { <br>      number, letter in print(&quot;\(user), \(pass)&quot;) }<br><br>//  Possible output if emission order is N-N-L-N-L-L:<br>//  2, A<br>//  3, A<br>//  3, B<br>//  3, C<br></pre><p>In this case when numbers emits for the first time letters has never emitted, so the second time. Then when letters finally emits, last value of number was 2, so (2, A) and so on.</p><p><strong>Operators for managing asynchronous operations</strong></p><p>When a Publisher itself generates other Publishers, specific operators are needed to handle these situations.</p><p>The <strong><em>flatMap</em></strong> operator transforms each received element into a new Publisher and merges their results into a single stream. It is especially useful when each event needs to trigger a new asynchronous request.</p><p>It is important to highlight that flatMap operates asynchronously. For each value emitted by the upstream publisher, it initiates a new independent asynchronous operation, which runs concurrently with the others.</p><p>This operator is among the most commonly used and perhaps also the most complex to truly understand. I would like to spend a bit more time on it, going through some deeper reasoning to cover it fully.</p><p>Let’s imagine we have the method used earlier to introduce the concept of Future:</p><pre>func fetchImage(withID id: String) -&gt; Future&lt;Image, Error&gt; {<br>    return Future { promise in<br>        networkClient.requestImage(id) { result in<br>            promise(result)<br>        }<br>    }<br>}</pre><p>Now let’s imagine we have a list of IDs corresponding to images that are available and need to be downloaded. Our application displays a list of IDs, and when the user taps on a single ID it triggers a full image download.</p><p>To model the user interaction, we use a PassthroughSubject that emits the selected image identifier:</p><pre>let selectedImageID = PassthroughSubject&lt;String, Never&gt;()<br><br>selectedImageID<br>    .flatMap { id in<br>        fetchImage(withID: id)<br>    }<br>    .sink(<br>        receiveCompletion: { completion in<br>            print(completion)<br>        },<br>        receiveValue: { image in<br>            print(image)<br>        }<br>    )</pre><p><strong>Why not use a simple <em>map</em>?</strong></p><pre>selectedImageID<br>    .map { id in<br>        fetchImage(withID: id)<br>    }<br>    .sink { value in<br>        print(value)<br>    }</pre><p>The fundamental difference between <em>map</em> and <em>flatMap</em> in this context is:</p><ul><li>map transforms a value into a new publisher, creating a nested structure: Publisher&lt;Future&lt;Image, Error&gt;&gt;</li><li>flatMap transforms a value into a publisher and then flattens the result into a single stream: Publisher&lt;Image&gt; <br><em>(Disclaimer: it’s not really like this, but you will understand after when </em><strong><em>eraseToAnyPublisher</em></strong><em> will be explained)</em></li></ul><p>In this case, <em>flatMap</em> transforms each emitted ID into a new asynchronous operation and then flattens the resulting publishers into a single stream of values.</p><p>An important characteristic of <em>flatMap</em> is that it does not serialize these operations. Instead, it creates multiple concurrent asynchronous calls, one for each emitted value. This means that if the user taps on multiple image IDs in a short time interval, <em>flatMap</em> will trigger multiple network requests in parallel, each independently executing its own Future.</p><p>The <strong><em>switchToLatest</em></strong> operator is a specialised variant that keeps only the most recent Publisher active, cancelling all previous ones. This behaviour is ideal for implementing real-time search functionality, where results from outdated queries are no longer relevant.</p><pre>var query = CurrentValueSubject&lt;String, Never&gt;()<br><br>query.map {<br>    api.search(query: $0)<br>}<br>.switchToLatest()</pre><p>If user types into a UITextView associated to this publisher, every inserted letter should emit a new value and it could initiate a new api call that stays active until the api response. So in this next case I could wrongly start 5 different api calls.</p><pre>// WITHOUT switchToLatest()<br>&quot;s&quot; -&gt; api.search(query: &quot;s&quot;)<br>&quot;sw&quot; -&gt; api.search(query: &quot;sw&quot;)<br>&quot;swi&quot; -&gt; api.search(query: &quot;swi&quot;)<br>&quot;swif&quot; -&gt; api.search(query: &quot;swif&quot;)<br>&quot;swift&quot; -&gt; api.search(query: &quot;swift&quot;)<br><br>5 RESULTS<br><br>// WITH switchToLatest()<br>&quot;s&quot; -&gt; api.search(query: &quot;s&quot;)<br><br>&quot;sw&quot; -&gt;    api.search(query: &quot;s&quot;) DELETED<br>           api.search(query: &quot;sw&quot;)<br><br>&quot;swi&quot; -&gt;   api.search(query: &quot;sw&quot;) DELETED<br>           api.search(query: &quot;swi&quot;)<br>          <br>&quot;swif&quot; -&gt;  api.search(query: &quot;swi&quot;) DELETED<br>           api.search(query: &quot;swif&quot;)<br><br>&quot;swift&quot; -&gt; api.search(query: &quot;swif&quot;) DELETED<br>           api.search(query: &quot;swift&quot;)<br><br>1 RESULT</pre><p><strong>Time-based operators</strong></p><p>In the context of user interaction, time-based operators play a particularly important role.</p><p>The <strong><em>debounce</em></strong> operator introduces a delay before emitting a value, checking that no further events have arrived during that interval. It is commonly used in search fields to avoid firing a network request on every single keystroke.</p><pre>.debounce(<br>    for: .seconds(TIME),<br>    scheduler: RunLoop.main<br>)</pre><p>The <strong><em>throttle</em></strong> operator, instead, limits the maximum number of events that can be emitted within a given time window. This approach is useful for controlling very frequent events, such as location updates or user gestures.</p><pre>.throttle(<br> for: .seconds(TIME),<br> scheduler: RunLoop.main,<br> latest: true<br>)</pre><p>The main diference between these two operators is that debounce waits for the silcence. If there is TIME seconds of silence, then the code is executed.</p><p>Thtottle, instead, emits only every TIME seconds if there is a new value to emit.<br>Latest is a boolean value that indicates whether to publish the most recent element. If <em>false</em>, the publisher emits the first element received during the interval.</p><p><strong>Error handling</strong></p><p>Combine provides several tools for managing errors.</p><p>The <strong><em>catch</em></strong> operator intercepts an error and replaces the failed Publisher with an alternative one.</p><pre>api.fetchUsers()<br>    .catch { error in<br>        // DO EVERYTHING YOU WANT TO HANDLE THE ERROR LIKE A NORMAL CATCH<br>    }<br>    .sink { users in<br>        print(users)<br>    }</pre><p>The <strong><em>replaceError</em></strong> operator substitutes an error with a default value, simplifying the handling of scenarios where a failure should not interrupt the application flow.</p><pre>api.fetchUsers()<br>    .replaceError(with: [])<br>    .sink { users in<br>        print(users)<br>    }</pre><p><em>replaceError</em> and <em>catch</em> are both used in Combine to handle failure cases, but they differ significantly in terms of flexibility and level of control.</p><p><em>replaceError</em> is the simplest form of error handling. It ignores the error itself and replaces any failure with a predefined static value. When an error occurs, the stream is terminated and substituted with this fallback value. This makes it suitable in situations where the error does not carry meaningful business logic and where a single default output is sufficient to keep the pipeline consistent.</p><p>In contrast, <em>catch</em> provides a more powerful and flexible mechanism. Instead of simply replacing the error with a value, it intercepts the failure and allows the developer to return a completely new publisher. This enables dynamic recovery strategies, such as switching to an alternative data source, returning a cached value, or executing a different asynchronous workflow. Importantly, it also allows the error context to be considered when deciding how to recover.</p><p>In summary, <em>replaceError</em> should be used when a simple and static fallback is sufficient and the error can safely be ignored, whereas <em>catch</em> is appropriate when error handling requires more complex logic, alternative execution paths, or full replacement of the original publishing pipeline.</p><p>The <strong><em>retry</em></strong> operator automatically retries a failed operation, making it particularly useful for network calls subject to transient issues.</p><pre>api.fetchUsers() <br>  .retry(3) <br>  .sink( receiveCompletion: { print($0) }, receiveValue: { print($0) } )</pre><p><strong>Thread management</strong></p><p>Modern applications often require running intensive operations in the background while updating the UI on the main thread.</p><p>The <strong><em>subscribe(on:)</em></strong> operator defines the execution context for operations upstream in the pipeline, while <strong><em>receive(on:) </em></strong>specifies the thread on which results should be received.</p><p>Using these operators correctly allows you to keep the interface responsive while avoiding any blocking of the main thread.</p><pre>api.fetchUsers()<br>    .subscribe(on: DispatchQueue.global())<br>    .sink(<br>        receiveCompletion: { _ in },<br>        receiveValue: { users in<br>            print(users)<br>        }<br>    )</pre><pre>api.fetchUsers()<br>    .receive(on: DispatchQueue.main)<br>    .sink(<br>        receiveCompletion: { _ in },<br>        receiveValue: { users in<br>            self.users = users<br>        }<br>    )</pre><p><em>receive(on:)</em> is usually used to apply UI updates because you must explicitly ensure that any UI-related work is executed on the main thread.</p><p><strong>Type Erasure and API Design in Combine</strong></p><p>I believe that as the last subsection of this chapter, it is necessary to discuss a topic that is somewhat complex but can only be fully understood after working through all of these operators and grasping their real purpose.</p><p>In Combine, every operator applied to a publisher produces a new publisher type. As pipelines become more complex, especially when combining asynchronous operations such as flatMap, map, or retry, the resulting type can become highly nested and dependent on the internal implementation details of the chain itself.</p><p>To address this issue, Combine provides the operator eraseToAnyPublisher(), whose purpose is not to modify the behaviour of the stream, but to hide its concrete type by converting it into a generic AnyPublisher&lt;Output, Failure&gt;.</p><p><strong>Why type erasure is needed</strong></p><p>Consider a typical UIKit scenario in which a PassthroughSubject is used to emit user-selected image identifiers, and each identifier triggers an asynchronous image download using a Future.</p><pre>let selectedImageID = PassthroughSubject&lt;String, Never&gt;()<br>func fetchImage(withID id: String) -&gt; Future&lt;Image, Error&gt; {<br>    return Future { promise in<br>        networkClient.requestImage(id) { result in<br>            promise(result)<br>        }<br>    }<br>}</pre><p>A natural implementation uses flatMap to transform each emitted identifier into an asynchronous request:</p><pre>selectedImageID<br>    .flatMap { id in<br>        fetchImage(withID: id)<br>    }</pre><p>Although this code is correct from a functional point of view, the resulting type of the pipeline is not a simple publisher. Instead, Swift infers a complex nested type such as Publishers.FlatMap&lt;Future&lt;Image, Error&gt;, PassthroughSubject&lt;String, Never&gt;&gt;.</p><p>This type is valid but problematic in architectural terms, as it exposes implementation details of the pipeline, makes function signatures hard to read, tightly couples the caller to Combine’s internal type system, and becomes unstable if any operator in the chain changes.</p><p><strong>Applying eraseToAnyPublisher()</strong></p><p>To solve this issue, eraseToAnyPublisher() is applied at the boundary of the abstraction:</p><pre>func imageStream() -&gt; AnyPublisher&lt;Image, Error&gt; {<br>    selectedImageID<br>        .flatMap { id in<br>            fetchImage(withID: id)<br>        }<br>        .eraseToAnyPublisher()<br>}</pre><p>In this case, the returned type is simplified to AnyPublisher&lt;Image, Error&gt;. This means that the caller no longer needs to know that a PassthroughSubject is used internally, that a Future wraps the asynchronous operation, or that flatMap is responsible for merging multiple asynchronous calls. The only visible contract is: a stream of Image values that may fail with an Error.</p><p><strong>Important clarification: it is not tied to flatMap</strong></p><p>A common misconception is that eraseToAnyPublisher() is required when using flatMap. This is not correct.</p><p>The need for type erasure does not depend on a specific operator, but rather on architectural boundaries.</p><p>For example, even a simple pipeline may require type erasure if it is exposed as part of a public API:</p><pre>func usernameStream() -&gt; AnyPublisher&lt;String, Never&gt; {<br>    Just(&quot;Guest&quot;)<br>        .eraseToAnyPublisher()<br>}</pre><p>Conversely, a complex flatMap chain does not necessarily require it if it is used internally:</p><pre>selectedImageID<br>    .flatMap { id in<br>        fetchImage(withID: id)<br>    }<br>    .sink { image in<br>        print(image)<br>    }</pre><p>In this case, the pipeline is not exposed, so preserving the concrete type is not an issue.</p><p><strong>When should eraseToAnyPublisher() be used?</strong></p><p>A practical rule is the following: eraseToAnyPublisher() should be used when a Combine pipeline crosses a module or architectural boundary and needs to expose a stable and simplified interface.</p><p>Typical use cases include ViewModels exposing outputs to ViewControllers, services exposing networking layers, repositories abstracting persistence logic, and public APIs that should not leak implementation details.</p><p><strong>When should it NOT be used?</strong></p><p>Type erasure should be avoided when the publisher is used only internally within a class or function, when preserving type information is useful for debugging or composition, or when performance-critical chains should avoid unnecessary abstraction layers. Unnecessary use of eraseToAnyPublisher() can reduce readability during development, since it hides useful information about the pipeline structure.</p><p>The role of eraseToAnyPublisher() is architectural rather than functional. It does not change how data flows through the system. Instead, it defines what the system exposes to the outside world.</p><p>In the selectedImageID example, flatMap is responsible for transforming each user interaction into an asynchronous image request, potentially resulting in multiple concurrent network operations. However, the complexity introduced by this chain is not the reason to use eraseToAnyPublisher().</p><p>Instead, type erasure is applied because the ViewModel, or service layer, should expose only a clean and stable contract: a stream of images, independent of how they are produced internally.</p><p>This separation between implementation and interface is one of the key principles for building scalable Combine-based architectures in UIKit applications.</p><p><strong>Let’s go back to fun-coding: the final result</strong></p><p>And here we are at last. After this substantial, technical but necessary digression on Combine, we can finally rewrite our MVVM code in a way that removes those unwieldy delegates and fully integrates reactive programming.</p><p>This code will introduce some additional constructs that are new to us, but they will be covered in detail immediately after the code itself.</p><pre>import UIKit<br>import Combine<br><br>// MARK: - Service<br><br>extension UserService {<br>    // Wraps the old completion-based search into a Combine publisher.<br>    // Deferred creates a new Future for every subscription,<br>    // so that retry can really perform the request again.<br>    func searchPublisher(query: String) -&gt; AnyPublisher&lt;[User], Error&gt; {<br>        Deferred {<br>            Future { promise in<br>                self.search(query: query) { result in<br>                    promise(result)<br>                }<br>            }<br>        }<br>        .eraseToAnyPublisher()<br>    }<br>}<br><br>// MARK: - ViewModel<br><br>final class UsersViewModel {<br><br>    // Inputs: what the view sends<br>    let searchText = CurrentValueSubject&lt;String, Never&gt;(&quot;&quot;)<br>    let exportTapped = PassthroughSubject&lt;Void, Never&gt;()<br><br>    // Outputs: what the view observes<br>    let users = CurrentValueSubject&lt;[User], Never&gt;([])<br>    let errorMessage = PassthroughSubject&lt;String, Never&gt;()<br><br>    var isExportEnabled: AnyPublisher&lt;Bool, Never&gt; {<br>        users<br>            .combineLatest(isLoading)<br>            .map { users, isLoading in !isLoading &amp;&amp; !users.isEmpty }<br>            .removeDuplicates()<br>            .eraseToAnyPublisher()<br>    }<br><br>    private let isLoading = CurrentValueSubject&lt;Bool, Never&gt;(false)<br>    private let service: UserService<br>    private var currentUsers: [User] = []<br>    private var cancellables = Set&lt;AnyCancellable&gt;()<br><br>    init(service: UserService = UserService()) {<br>        self.service = service<br>        bind()<br>    }<br><br>    private func bind() {<br>        searchText<br>            .debounce(for: .milliseconds(300), scheduler: RunLoop.main) <br>                // wait until the user stops typing<br>            .removeDuplicates()                                          <br>                // skip if the text has not changed<br>            .map { [unowned self] text in<br>                self.search(text)                                        <br>                // a new request for each text<br>            }<br>            .switchToLatest()                                            <br>                // discard older searches<br>            .receive(on: DispatchQueue.main)                             <br>                // back to the main thread<br>            .sink { [unowned self] users in<br>                self.currentUsers = users<br>                self.isLoading.send(false)<br>                self.users.send(users)<br>            }<br>            .store(in: &amp;cancellables)<br><br>        exportTapped<br>            .sink { [unowned self] in<br>                print(&quot;Exporting \(self.currentUsers.count) users&quot;)<br>            }<br>            .store(in: &amp;cancellables)<br>    }<br><br>    // Starts a single search and turns a failure into an empty list,<br>    // so that one failed request does not stop the whole search stream<br>    private func search(_ text: String) -&gt; AnyPublisher&lt;[User], Never&gt; {<br>        isLoading.send(true)<br>        return service.searchPublisher(query: text)<br>            .retry(2) <br>            .catch { [weak self] error -&gt; Just&lt;[User]&gt; in<br>                self?.errorMessage.send(error.localizedDescription)<br>                return Just([])<br>            }<br>            .eraseToAnyPublisher()<br>    }<br>}<br><br>// MARK: - View<br><br>final class UsersViewController: UIViewController, UITableViewDataSource {<br><br>    private let viewModel: UsersViewModel<br>    private var users: [User] = []<br>    private var cancellables = Set&lt;AnyCancellable&gt;()<br><br>    private let searchField = UITextField()<br>    private let tableView = UITableView()<br>    private let exportButton = UIButton(type: .system)<br><br>    init(viewModel: UsersViewModel) {<br>        self.viewModel = viewModel<br>        super.init(nibName: nil, bundle: nil)<br>    }<br><br>    required init?(coder: NSCoder) {<br>        fatalError(&quot;init(coder:) has not been implemented&quot;)<br>    }<br><br>    override func viewDidLoad() {<br>        super.viewDidLoad()<br>        setupViews() // same as the MVC version<br>        bind()<br>    }<br><br>    // MARK: - ViewModel -&gt; View<br>    private func bind() {<br>        viewModel.users<br>            .sink { [weak self] users in<br>                self?.users = users<br>                self?.tableView.reloadData()<br>            }<br>            .store(in: &amp;cancellables)<br><br>        viewModel.isExportEnabled<br>            .receive(on: DispatchQueue.main)<br>            .sink { [weak self] isEnabled in<br>                self?.exportButton.isEnabled = isEnabled<br>            }<br>            .store(in: &amp;cancellables)<br><br>        viewModel.errorMessage<br>            .receive(on: DispatchQueue.main)<br>            .sink { [weak self] message in<br>                self?.showError(message) // same as the MVC version<br>            }<br>            .store(in: &amp;cancellables)<br>    }<br><br>    // MARK: - View -&gt; ViewModel<br>    @objc private func searchTextChanged() {<br>        viewModel.searchText.send(searchField.text ?? &quot;&quot;)<br>    }<br><br>    @objc private func exportTapped() {<br>        viewModel.exportTapped.send()<br>    }<br><br>    // MARK: - UITableViewDataSource<br>    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -&gt; Int {<br>        users.count<br>    }<br><br>    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -&gt; UITableViewCell {<br>        let cell = tableView.dequeueReusableCell(withIdentifier: &quot;UserCell&quot;, for: indexPath)<br>        let user = users[indexPath.row]<br>        var content = cell.defaultContentConfiguration()<br>        content.text = user.name<br>        content.secondaryText = user.email<br>        cell.contentConfiguration = content<br>        return cell<br>    }<br>}</pre><p><strong>What did we gain?</strong></p><p>Let’s put this code next to the “old school” view model we wrote at the beginning of the Combine chapter. The behaviour is the same: the app waits for the user to stop typing, skips identical searches, ignores outdated responses, retries failed requests, updates the UI on the main thread and keeps the button consistent. What changed is everything around it.</p><p>First of all, the flow can finally be read the way we think about it. The search pipeline goes from top to bottom exactly like the arrows we drew earlier. Each line is one step of the chain: wait, skip duplicates, search, retry if needed, keep only the latest result, go back to the main thread, deliver it. In the previous version, the same logic was spread across a Timer callback, a guard, a UUID check, a recursive function and a DispatchQueue.main.async, and you had to jump through the whole file to reconstruct it.</p><p>Second, most of the hand-written state is gone. There is no Timer to invalidate, no lastQuery to remember and reset, no request identifier to compare and no attempt counter to increment. These were exactly the variables where bugs tend to hide, like the lastQuery = nil we had to add in the error branch so that the same text could be searched again. Each of them is now replaced by an operator that does one thing and does it the same way every time.</p><p>Third, the state of the button is no longer something we have to remember to update. Before, every place that changed users or isLoading also had to call notifyExportState(), and forgetting a single call was enough to leave the button in the wrong state. Now isExportEnabled is derived from users and isLoading through combineLatest, so it simply cannot disagree with them.</p><p>Fourth, the delegate protocol has disappeared. The view model now exposes a few inputs and outputs, and the view controller does only what a “dumb” view should do: it forwards user actions to the inputs and reacts to the outputs. Adding a new piece of information for the view no longer means adding a new method to a protocol and implementing it; it simply means exposing one more publisher.</p><p>Finally, the lifecycle is handled for us. Every subscription is stored in cancellables, and when the view model or the view controller is deallocated, everything is cancelled automatically. There is no deinit to remember and no pending callback that wakes up on an object that no longer exists.</p><p>The result is shorter, easier to read and much harder to break when the next requirement arrives. And that is the real point: requirements always arrive.</p><p><strong>Conclusion</strong></p><p>At the beginning of this article we asked why so many companies look for developers who know UIKit and Combine, when the world seems to be moving toward SwiftUI. The answer is now concrete. A large UIKit codebase cannot be rewritten overnight, but it can still move to MVVM and reactive programming, one screen at a time. Combine is what makes this possible: it replaces delegates, timers, flags and nested callbacks with a single, readable flow of data.</p><p>It is also not a skill tied to the past. Publishers, subscribers, operators and the idea of a view that simply reacts to state are the same concepts that SwiftUI is built on. Learning Combine on a UIKit project means learning to think reactively, and that stays useful whatever UI framework you end up working with.</p><p><em>Disclaimer: it is only fair to say that the entire content of this document comes from me. For the sake of clarity, I decided to refine some parts of the text with the help of a generative AI tool, just to ensure the best possible phrasing. I hope you enjoyed this article. Never stop coding!</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a875bdb13a6e" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>