[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M6E67WHG6FXMJ3HFH66WFP8P":3,"skill-same:01M6E67WHG6FXMJ3HFH66WFP8P":64},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":18,"publishedAt":33,"linkOnly":34,"markdownContent":35,"markdownBody":36,"frontMatter":37,"refName":41,"commitSha":42,"skillDirectory":43,"forksCount":44,"repositoryHtmlUrl":45,"repositoryHomepageUrl":46,"ownerHtmlUrl":47,"ownerBlogUrl":6,"ownerDescription":48,"updatedAt":49,"install":50,"resources":63},"01M6E67WHG6FXMJ3HFH66WFP8P","axiom-combine-patterns",null,"Use when working with Combine publishers, AnyCancellable lifecycle, @Published properties, or bridging Combine with async\u002Fawait. Covers reactive patterns, operator selection, memory management, and migration strategy.","ComeOnOliver\u002Fskillshub","ComeOnOliver","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F43215937?v=4","01M6E5JNFECJAAVFE0W7SMWWD2","Haoran Shu","01M6E5JNNDQS7AJZDYFQ8TPZCK",67,"MIT","https:\u002F\u002Fgithub.com\u002FComeOnOliver\u002Fskillshub\u002Fblob\u002Fmain\u002Fskills\u002FCharlesWiltgen\u002FAxiom\u002Faxiom-combine-patterns\u002FSKILL.md",[],[19,20,21,22,23,24,25,26,27,28,29,30,31,32],"patterns","axiom combine patterns","memory","operator","lifecycle","strategy","management","use","migration","async","properties","selection","memory management","bridging","2026-11-10 10:12:30",false,"---\nname: axiom-combine-patterns\ndescription: Use when working with Combine publishers, AnyCancellable lifecycle, @Published properties, or bridging Combine with async\u002Fawait. Covers reactive patterns, operator selection, memory management, and migration strategy.\nlicense: MIT\nmetadata:\n  version: \"1.0.0\"\n  last-updated: \"2026-03-12\"\n---\n\n# Combine Patterns\n\n## Overview\n\nCombine remains embedded in massive production codebases — UIKit delegates, NotificationCenter bridging, KVO observation, and @Published properties are everywhere. New code prefers async\u002Fawait, but interop and maintenance of existing Combine pipelines is daily work. This skill covers the decisions and pitfalls that matter: when to use Combine vs async\u002Fawait, how to avoid memory leaks, and how to bridge between the two paradigms.\n\n**Core principle**: Combine is not dead — it's mature. The question isn't \"should I use Combine?\" but \"is Combine the right tool for THIS specific data flow?\"\n\n## When to Use This Skill\n\n- Working with existing Combine pipelines\n- Deciding between Combine and async\u002Fawait for a new data flow\n- Debugging AnyCancellable memory leaks or silent pipeline failures\n- Using @Published or ObservableObject\n- Bridging Combine publishers with async\u002Fawait code\n- Working with Subjects (PassthroughSubject, CurrentValueSubject)\n\n## When NOT to Use This Skill\n\n- Timer.publish patterns → route via `axiom-ios-concurrency` to timer-patterns skill (dedicated timer lifecycle coverage)\n- @Observable migration from ObservableObject → use `axiom-swift-concurrency` (modern observation)\n- UIKit ↔ SwiftUI bridging → route via `axiom-ios-ui` (view wrapping, not data flow)\n- General async\u002Fawait patterns → use `axiom-swift-concurrency`\n\n## Example Prompts\n\n- \"Should I use Combine or async\u002Fawait for this?\"\n- \"My Combine pipeline silently stops producing values\"\n- \"How do I convert a publisher to an async sequence?\"\n- \"AnyCancellable is leaking — where do I store it?\"\n- \"What's the difference between combineLatest and zip?\"\n- \"How do I debounce a text field with Combine?\"\n- \"My @Published property update isn't reaching the view\"\n- \"How do I bridge a Combine publisher into async\u002Fawait code?\"\n\n---\n\n## Part 1: Combine vs async\u002Fawait Decision Tree\n\n| Use Case | Combine | async\u002Fawait | Why |\n|----------|---------|-------------|-----|\n| One-shot network call | No | Yes | async\u002Fawait is simpler, no cancellable management |\n| Stream of values over time | Yes | AsyncStream | Combine's operators (debounce, combineLatest) are richer |\n| Debounce\u002Fthrottle user input | Yes | Awkward | Combine has built-in debounce\u002Fthrottle; AsyncStream requires manual implementation |\n| Merge multiple sources | Yes | TaskGroup | Combine's merge\u002FcombineLatest handle heterogeneous streams naturally |\n| Existing UIKit KVO\u002FNotification | Yes | Bridge | publisher(for:) and NotificationCenter.default.publisher are idiomatic Combine |\n| New project iOS 17+ | No | Yes | @Observable + async\u002Fawait is the modern pattern |\n| Existing codebase with Combine | Maintain | Migrate incrementally | Don't rewrite working pipelines — bridge at boundaries |\n\n### Quick Decision\n\n```\nIs it a one-shot operation (network call, file read)?\n├─ Yes → async\u002Fawait (simpler, no cancellable management)\n│\nDoes it need time-based operators (debounce, throttle, delay)?\n├─ Yes → Combine (built-in operators, no manual implementation)\n│\nAre you combining multiple ongoing streams?\n├─ Yes → Combine (combineLatest, merge, zip are purpose-built)\n│\nIs this new code on iOS 17+?\n├─ Yes → async\u002Fawait + @Observable (modern pattern)\n│\nIs it existing Combine code that works?\n└─ Yes → Keep it. Bridge at boundaries when async\u002Fawait code needs the data.\n```\n\n---\n\n## Part 2: Publisher\u002FSubscriber Lifecycle\n\n### AnyCancellable Storage Rules\n\nAnyCancellable cancels its subscription when deallocated. If you don't store it, the pipeline is cancelled immediately after setup.\n\n#### ❌ Pipeline dies instantly\n\n```swift\nfunc setupPipeline() {\n    publisher\n        .sink { value in\n            self.handle(value)  \u002F\u002F Never called\n        }\n    \u002F\u002F AnyCancellable returned by sink is discarded → subscription cancelled\n}\n```\n\n#### ✅ Store in Set\u003CAnyCancellable>\n\n```swift\nprivate var cancellables = Set\u003CAnyCancellable>()\n\nfunc setupPipeline() {\n    publisher\n        .sink { [weak self] value in\n            self?.handle(value)\n        }\n        .store(in: &cancellables)\n}\n```\n\n### Why Set, Not Array\n\n`Set\u003CAnyCancellable>` is the idiomatic choice because:\n- `store(in:)` works with both `Set` and `RangeReplaceableCollection` (including `Array`), but `Set` is conventional\n- Order doesn't matter for subscriptions\n- Prevents accidental duplicates if setup runs twice\n\n### 4 Memory Leak Patterns\n\n#### Leak 1: Strong self in sink\n\n```swift\n\u002F\u002F ❌ LEAK: sink closure captures self strongly\npublisher\n    .sink { value in\n        self.handle(value)  \u002F\u002F Strong capture → retain cycle\n    }\n    .store(in: &cancellables)\n\n\u002F\u002F ✅ FIX: weak self\npublisher\n    .sink { [weak self] value in\n        self?.handle(value)\n    }\n    .store(in: &cancellables)\n```\n\n#### Leak 2: Missing store(in:)\n\n```swift\n\u002F\u002F ❌ LEAK: cancellable assigned to local var, not stored\nlet cancellable = publisher.sink { handle($0) }\n\u002F\u002F cancellable deallocated at end of scope → pipeline cancelled\n\n\u002F\u002F ✅ FIX: store in instance property\npublisher.sink { [weak self] in self?.handle($0) }\n    .store(in: &cancellables)\n```\n\n#### Leak 3: Over-retained cancellables\n\n```swift\n\u002F\u002F ❌ LEAK: cancellables set never cleared, old pipelines accumulate\nfunc refreshData() {\n    \u002F\u002F Each call adds another subscription without removing the previous one\n    dataPublisher\n        .sink { [weak self] in self?.update($0) }\n        .store(in: &cancellables)\n}\n\n\u002F\u002F ✅ FIX: clear before re-subscribing\nfunc refreshData() {\n    cancellables.removeAll()  \u002F\u002F Cancel previous subscriptions\n    dataPublisher\n        .sink { [weak self] in self?.update($0) }\n        .store(in: &cancellables)\n}\n```\n\n#### Leak 4: assign(to:on:) strong capture\n\n`assign(to:on:)` captures the `on:` parameter **strongly**. When the target is `self`, you get a retain cycle: `self → cancellables → subscription → self`.\n\n```swift\n\u002F\u002F ❌ LEAK: assign(to:on:) retains self strongly — deinit never called\nuserPublisher\n    .map { $0.name }\n    .assign(to: \\.displayName, on: self)\n    .store(in: &cancellables)\n\n\u002F\u002F ✅ FIX: use assign(to:) with @Published projected value (iOS 14+)\nuserPublisher\n    .map { $0.name }\n    .assign(to: &$displayName)\n\u002F\u002F No store(in:) needed — subscription tied to @Published property lifetime\n```\n\nKey difference: `assign(to: &$prop)` does NOT return an `AnyCancellable` — the subscription is managed internally and cancelled when the `@Published` property's owner deallocates. No retain cycle, no cancellable storage needed.\n\nIf you must support iOS 13, use `sink` with `[weak self]` instead.\n\n---\n\n## Part 3: Essential Operators\n\nOne canonical example per group. These cover 90% of real-world usage.\n\n### Transform\n\n```swift\n\u002F\u002F map: transform each value\npublisher.map { $0.name }\n\n\u002F\u002F compactMap: transform + filter nil\npublisher.compactMap { Int($0) }\n\n\u002F\u002F flatMap: one-to-many (each value produces a new publisher)\nsearchText\n    .flatMap { query in\n        api.search(query)  \u002F\u002F Returns a publisher\n    }\n```\n\n**flatMap gotcha**: Without `.switchToLatest()` or `maxPublishers: .max(1)`, flatMap creates a new inner publisher for every upstream value. For search-as-you-type, use `map` + `switchToLatest` instead:\n\n```swift\nsearchText\n    .map { query in api.search(query) }\n    .switchToLatest()  \u002F\u002F Cancels previous search when new query arrives\n```\n\n### Combine Multiple Sources\n\n```swift\n\u002F\u002F combineLatest: latest value from each, fires when ANY changes\nPublishers.CombineLatest(namePublisher, agePublisher)\n    .map { name, age in \"\\(name), \\(age)\" }\n\n\u002F\u002F merge: interleave values from same-type publishers\nPublishers.Merge(localUpdates, remoteUpdates)\n    .sink { update in handle(update) }\n\n\u002F\u002F zip: pairs values 1:1 (waits for both to produce)\nPublishers.Zip(requestA, requestB)\n    .sink { responseA, responseB in \u002F* both complete *\u002F }\n```\n\n| Operator | Fires When | Use Case |\n|----------|-----------|----------|\n| combineLatest | Any input changes | Form validation (all fields) |\n| merge | Any input produces | Combining event streams |\n| zip | All inputs produce one value | Parallel requests that must complete together |\n\n### Time-Based\n\n```swift\n\u002F\u002F debounce: wait until values stop arriving (search-as-you-type)\nsearchTextPublisher\n    .debounce(for: .milliseconds(300), scheduler: RunLoop.main)\n    .sink { [weak self] query in self?.search(query) }\n    .store(in: &cancellables)\n\n\u002F\u002F throttle: emit at most once per interval (scroll position)\nscrollOffsetPublisher\n    .throttle(for: .milliseconds(100), scheduler: RunLoop.main, latest: true)\n    .sink { [weak self] offset in self?.updateHeader(offset) }\n    .store(in: &cancellables)\n```\n\n| Operator | Behavior | Use Case |\n|----------|----------|----------|\n| debounce | Waits for silence, then emits last value | Search fields, auto-save |\n| throttle(latest: true) | Emits latest value at fixed intervals | Scroll tracking, sensor data |\n| throttle(latest: false) | Emits first value at fixed intervals | Rate-limiting button taps |\n\n### Error Handling\n\n```swift\n\u002F\u002F tryMap: transform that can throw\npublisher.tryMap { data in\n    try JSONDecoder().decode(Model.self, from: data)\n}\n\n\u002F\u002F mapError: convert error types\npublisher.mapError { error in\n    AppError.network(error)\n}\n\n\u002F\u002F replaceError: provide fallback value (terminates error path)\npublisher.replaceError(with: defaultValue)\n\n\u002F\u002F retry: re-subscribe on failure\npublisher.retry(3)  \u002F\u002F Retry up to 3 times before propagating error\n```\n\n**Error handling order matters**: `retry` should come before `replaceError`. Retry re-subscribes to the upstream publisher; replaceError terminates the error and makes the pipeline infallible.\n\n```swift\napi.fetchData()\n    .retry(3)                    \u002F\u002F Try 3 more times on failure\n    .replaceError(with: cached)  \u002F\u002F If all retries fail, use cache\n    .sink { data in update(data) }\n    .store(in: &cancellables)\n```\n\n**replaceError after flatMap kills the outer pipeline**: If `replaceError` is downstream of `flatMap`, a single inner publisher error terminates the entire pipeline — not just that one request. Move error handling inside `flatMap` so each inner publisher handles its own errors:\n\n```swift\n\u002F\u002F ❌ One API error kills the entire pipeline\n$searchText\n    .flatMap { query in api.search(query) }\n    .replaceError(with: [])  \u002F\u002F Pipeline completes on first error\n    .sink { ... }\n\n\u002F\u002F ✅ Each search handles its own errors independently\n$searchText\n    .flatMap { query in\n        api.search(query)\n            .replaceError(with: [])  \u002F\u002F Only this search affected\n    }\n    .sink { ... }\n```\n\n---\n\n## Part 4: @Published + ObservableObject\n\n### willSet Timing\n\n`@Published` fires its publisher in `willSet`, not `didSet`. This means subscribers see the new value before the property has actually been set on the object.\n\n```swift\nclass ViewModel: ObservableObject {\n    @Published var count = 0\n\n    init() {\n        $count.sink { newValue in\n            \u002F\u002F 'newValue' is the incoming value\n            \u002F\u002F BUT self.count is still the OLD value here\n            print(\"New: \\(newValue), Current: \\(self.count)\")\n            \u002F\u002F Prints \"New: 1, Current: 0\" when count is set to 1\n        }\n        .store(in: &cancellables)\n    }\n}\n```\n\nIf you need to read the property's value after it's been set, don't subscribe to `$count` — use a `didSet` observer instead, or read `self.count` after a brief deferral. The `$` publisher is designed for reacting to the incoming value, not for reading post-mutation state.\n\n### Nested ObservableObject Trap\n\nSwiftUI does NOT observe nested ObservableObject changes. Only the top-level object's `objectWillChange` triggers view updates.\n\n```swift\n\u002F\u002F ❌ View won't update when settings.theme changes\nclass AppState: ObservableObject {\n    @Published var settings = Settings()  \u002F\u002F Settings is also ObservableObject\n}\n\nclass Settings: ObservableObject {\n    @Published var theme = \"light\"  \u002F\u002F Changes here don't propagate\n}\n\n\u002F\u002F ✅ FIX: Forward objectWillChange manually\nclass AppState: ObservableObject {\n    @Published var settings = Settings()\n    private var cancellables = Set\u003CAnyCancellable>()\n\n    init() {\n        settings.objectWillChange\n            .sink { [weak self] _ in\n                self?.objectWillChange.send()\n            }\n            .store(in: &cancellables)\n    }\n}\n```\n\n**Better fix for iOS 17+**: Migrate to `@Observable`, which handles nested observation automatically. See `axiom-swift-concurrency` for migration patterns.\n\n### Thread Safety Warning\n\n`@Published` is NOT thread-safe. Setting a `@Published` property from a background thread triggers `objectWillChange` off the main thread, which can crash SwiftUI views.\n\n```swift\n\u002F\u002F ❌ CRASH: @Published set from background thread\nclass ViewModel: ObservableObject {\n    @Published var data: [Item] = []\n\n    func fetch() {\n        Task {\n            let items = await api.fetchItems()\n            data = items  \u002F\u002F Background thread → crash\n        }\n    }\n}\n\n\u002F\u002F ✅ FIX: Ensure main thread\n@MainActor\nclass ViewModel: ObservableObject {\n    @Published var data: [Item] = []\n\n    func fetch() {\n        Task {\n            let items = await api.fetchItems()\n            data = items  \u002F\u002F Safe — @MainActor ensures main thread\n        }\n    }\n}\n```\n\n---\n\n## Part 5: Bridging Combine and async\u002Fawait\n\n### Publisher → AsyncSequence\n\nUse `.values` to consume any publisher as an async sequence:\n\n```swift\nlet cancellable = notificationPublisher\n    .sink { notification in handle(notification) }\n\n\u002F\u002F ✅ Modern equivalent using .values\nfor await notification in notificationPublisher.values {\n    handle(notification)\n}\n```\n\n**Caveats with `.values`**:\n- The `for await` loop runs indefinitely until the publisher completes or the Task is cancelled\n- Errors thrown by the publisher terminate the loop\n- Only one consumer — if two `for await` loops consume the same `.values`, behavior is undefined\n\n### async\u002Fawait → Publisher\n\nWrap an async function in `Future` for Combine consumption:\n\n```swift\nfunc fetchUser(id: String) async throws -> User { ... }\n\n\u002F\u002F Wrap as a Combine publisher\nlet userPublisher = Future\u003CUser, Error> { promise in\n    Task {\n        do {\n            let user = try await fetchUser(id: \"123\")\n            promise(.success(user))\n        } catch {\n            promise(.failure(error))\n        }\n    }\n}\n```\n\n**Future executes immediately** — it runs its closure when created, not when subscribed. Wrap in `Deferred` if you need lazy execution:\n\n```swift\nlet lazyPublisher = Deferred {\n    Future\u003CUser, Error> { promise in\n        Task {\n            do {\n                let user = try await fetchUser(id: \"123\")\n                promise(.success(user))\n            } catch {\n                promise(.failure(error))\n            }\n        }\n    }\n}\n```\n\n### Gradual Migration Strategy\n\nDon't rewrite working Combine code. Bridge at the boundary:\n\n```\nCombine pipeline  →  .values  →  async\u002Fawait code\n                     (bridge)\n\nasync function    →  Future   →  Combine pipeline\n                     (bridge)\n```\n\n**Migration priority**:\n1. New code: write in async\u002Fawait\n2. Boundary: bridge with `.values` or `Future`\n3. Existing Combine: leave working pipelines alone\n4. Rewrite: only when the pipeline needs significant changes anyway\n\n---\n\n## Part 6: Subjects\n\n### PassthroughSubject vs CurrentValueSubject\n\n| Feature | PassthroughSubject | CurrentValueSubject |\n|---------|-------------------|-------------------|\n| Initial value | None | Required |\n| Late subscribers | Miss previous values | Get current value immediately |\n| `.value` property | No | Yes (read current value) |\n| Use case | Events (button taps, notifications) | State (current selection, loading status) |\n\n```swift\n\u002F\u002F Event-driven: no initial value, late subscribers miss past events\nlet taps = PassthroughSubject\u003CVoid, Never>()\ntaps.send()\n\n\u002F\u002F State-driven: always has a current value\nlet isLoading = CurrentValueSubject\u003CBool, Never>(false)\nisLoading.value = true  \u002F\u002F Direct access\nisLoading.send(false)   \u002F\u002F Also works\n```\n\n### Send-After-Completion Pitfall\n\nOnce a Subject receives a completion event, all subsequent `send()` calls are silently ignored. No crash, no error — just silence.\n\n```swift\nlet subject = PassthroughSubject\u003CInt, Never>()\n\nsubject.send(1)           \u002F\u002F Delivered\nsubject.send(completion: .finished)\nsubject.send(2)           \u002F\u002F Silently ignored — no crash, no warning\n\n\u002F\u002F This is the most common cause of \"my pipeline stopped working\"\n```\n\n**Diagnosis**: If a pipeline silently stops producing values, check whether anything upstream sent a `.finished` or `.failure` completion. Once complete, the pipeline is dead.\n\n---\n\n## Part 7: Cold vs Hot Publishers (share\u002Fmulticast)\n\nMost Combine publishers are **cold** — they start work when subscribed and each subscriber gets its own independent execution. `URLSession.dataTaskPublisher` fires a new HTTP request per subscriber.\n\n```swift\n\u002F\u002F ❌ Two subscribers = two network requests\nlet publisher = URLSession.shared\n    .dataTaskPublisher(for: url)\n    .map(\\.data)\n    .eraseToAnyPublisher()\n\npublisher.sink { cache.store($0) }.store(in: &cancellables)  \u002F\u002F Request 1\npublisher.sink { display($0) }.store(in: &cancellables)       \u002F\u002F Request 2\n```\n\n### share()\n\n`.share()` makes a cold publisher hot — the first subscriber triggers the work, subsequent subscribers share the output:\n\n```swift\n\u002F\u002F ✅ One request, shared result\nlet publisher = URLSession.shared\n    .dataTaskPublisher(for: url)\n    .map(\\.data)\n    .share()\n    .eraseToAnyPublisher()\n\npublisher.sink { cache.store($0) }.store(in: &cancellables)  \u002F\u002F Triggers request\npublisher.sink { display($0) }.store(in: &cancellables)       \u002F\u002F Shares result\n```\n\n### share() Gotchas\n\n| Gotcha | Effect | Fix |\n|--------|--------|-----|\n| Late subscribers miss values | `share()` uses PassthroughSubject — no replay | Attach all subscribers before the first value arrives, or use `multicast` with `CurrentValueSubject` |\n| Upstream completed before subscriber attaches | Late subscriber immediately gets `.finished` with no values | Ensure subscription order, or cache the result outside Combine |\n| All subscribers cancel → upstream cancels | New subscriber after that triggers a NEW upstream execution | Expected behavior, but surprising if you assumed the result was cached |\n\n### When to use share()\n\n```\nMultiple subscribers to the same expensive publisher?\n├─ No → Don't use share() (unnecessary complexity)\n│\n├─ Yes, all subscribe at the same time?\n│   └─ Yes → share() works\n│\n└─ Yes, subscribers attach at different times?\n    └─ Use multicast(subject:) with CurrentValueSubject, or cache the result in a property\n```\n\n---\n\n## Anti-Rationalization\n\n| Thought | Reality |\n|---------|---------|\n| \"Combine is dead, just use async\u002Fawait\" | Combine has no deprecation notice. Thousands of production apps use it. Rewriting working pipelines wastes time and introduces bugs. Bridge incrementally instead. |\n| \"I'll just use .sink everywhere\" | Without `[weak self]` and proper `store(in:)`, every sink is a potential memory leak. The lifecycle rules in Part 2 prevent the top 4 leak patterns. |\n| \"assign(to:on:) is fine, it's the standard API\" | It captures `on:` strongly — retain cycle if target is `self`. Use `assign(to: &$prop)` instead (Part 2, Leak 4). |\n| \"debounce and throttle are the same thing\" | debounce waits for silence; throttle emits at intervals. Using the wrong one causes either delayed responses or missed events. Part 3 has the decision table. |\n| \"I know how @Published works\" | @Published fires on willSet, not didSet. Nested ObservableObject doesn't propagate. Background thread access crashes. Part 4 covers all three traps. |\n| \"I'll migrate everything to async\u002Fawait at once\" | Full rewrites of working Combine code introduce bugs and waste time. Bridge at boundaries (Part 5). Rewrite only when the pipeline needs significant changes anyway. |\n\n---\n\n## Pressure Scenarios\n\n### Scenario 1: \"Let's migrate all Combine code to async\u002Fawait\"\n\n**Setup**: Tech lead wants to modernize the codebase. \"Combine is legacy, let's rip it out.\"\n\n**Pressure**: Authority + scope creep. The entire data layer uses Combine publishers, @Published properties, and operator chains.\n\n**Expected with skill**: Push back with the gradual migration strategy (Part 5). New code uses async\u002Fawait. Boundaries use `.values` and `Future`. Existing working pipelines stay until they need changes. Full rewrite is the most expensive option with the least benefit.\n\n**Pushback template**: \"Combine isn't deprecated — Apple still ships it in every SDK. A full rewrite of working pipelines introduces bugs we don't have today. Let's bridge at boundaries: new code in async\u002Fawait, `.values` to consume existing publishers, and we only rewrite a pipeline when we're already changing it significantly.\"\n\n---\n\n### Scenario 2: \"Pipeline silently stopped — just recreate it\"\n\n**Setup**: A Combine pipeline stopped producing values after a refactor. No crash, no error.\n\n**Pressure**: Time pressure. \"Just tear it down and rebuild.\"\n\n**Expected with skill**: Diagnose before rebuilding. Check: (1) Was a completion sent upstream? (send-after-completion, Part 6). (2) Is the AnyCancellable still alive? (storage rules, Part 2). (3) Did the publisher error without handling? (replaceError \u002F catch, Part 3). These three causes cover 90% of silent pipeline failures.\n\n**Diagnostic checklist**:\n1. Is the `AnyCancellable` still stored? (Set not cleared, not deallocated)\n2. Did anything upstream send `.finished` or `.failure`?\n3. Is there a `tryMap` or other throwing operator without error handling?\n4. Was `switchToLatest` used where the outer publisher completed?\n\n**Pushback template**: \"Before rebuilding, let me check four things: cancellable lifecycle, upstream completions, unhandled errors, and switchToLatest completion. One of these is almost always the cause. It takes 5 minutes to diagnose vs 30 minutes to rebuild and test.\"\n\n---\n\n### Scenario 3: \"Settings changes aren't updating the UI\"\n\n**Setup**: A settings screen uses a nested ObservableObject. The parent `AppState` holds a `Settings` object. When the user changes `settings.theme`, the UI doesn't update.\n\n**Pressure**: \"The binding works in isolation, it must be a SwiftUI bug. Let me just force a refresh with objectWillChange.send().\"\n\n**Expected with skill**: Recognize the nested ObservableObject trap (Part 4). SwiftUI does NOT observe nested ObservableObject changes — only the top-level object's `objectWillChange` triggers view updates. The fix is either forwarding `objectWillChange` from the nested object, or migrating to `@Observable` (iOS 17+) which handles nesting automatically.\n\n**Anti-pattern without skill**: Sprinkling `objectWillChange.send()` calls throughout the code, adding `@Published` to every nested property (which doesn't help), or restructuring the model to flatten everything into one object (losing separation of concerns).\n\n**Pushback template**: \"SwiftUI only observes the top-level ObservableObject. Nested objects need their objectWillChange forwarded to the parent. Part 4 has the exact pattern — it's a 5-line fix in the parent's init, not a SwiftUI bug.\"\n\n---\n\n## Resources\n\n**WWDC**: 2019-722, 2019-721, 2020-10034\n\n**Docs**: \u002Fcombine, \u002Fcombine\u002Fanycancellable, \u002Fcombine\u002Fpublished\n\n**Skills**: swift-concurrency, memory-debugging\n\n","# Combine Patterns\n\n## Overview\n\nCombine remains embedded in massive production codebases — UIKit delegates, NotificationCenter bridging, KVO observation, and @Published properties are everywhere. New code prefers async\u002Fawait, but interop and maintenance of existing Combine pipelines is daily work. This skill covers the decisions and pitfalls that matter: when to use Combine vs async\u002Fawait, how to avoid memory leaks, and how to bridge between the two paradigms.\n\n**Core principle**: Combine is not dead — it's mature. The question isn't \"should I use Combine?\" but \"is Combine the right tool for THIS specific data flow?\"\n\n## When to Use This Skill\n\n- Working with existing Combine pipelines\n- Deciding between Combine and async\u002Fawait for a new data flow\n- Debugging AnyCancellable memory leaks or silent pipeline failures\n- Using @Published or ObservableObject\n- Bridging Combine publishers with async\u002Fawait code\n- Working with Subjects (PassthroughSubject, CurrentValueSubject)\n\n## When NOT to Use This Skill\n\n- Timer.publish patterns → route via `axiom-ios-concurrency` to timer-patterns skill (dedicated timer lifecycle coverage)\n- @Observable migration from ObservableObject → use `axiom-swift-concurrency` (modern observation)\n- UIKit ↔ SwiftUI bridging → route via `axiom-ios-ui` (view wrapping, not data flow)\n- General async\u002Fawait patterns → use `axiom-swift-concurrency`\n\n## Example Prompts\n\n- \"Should I use Combine or async\u002Fawait for this?\"\n- \"My Combine pipeline silently stops producing values\"\n- \"How do I convert a publisher to an async sequence?\"\n- \"AnyCancellable is leaking — where do I store it?\"\n- \"What's the difference between combineLatest and zip?\"\n- \"How do I debounce a text field with Combine?\"\n- \"My @Published property update isn't reaching the view\"\n- \"How do I bridge a Combine publisher into async\u002Fawait code?\"\n\n---\n\n## Part 1: Combine vs async\u002Fawait Decision Tree\n\n| Use Case | Combine | async\u002Fawait | Why |\n|----------|---------|-------------|-----|\n| One-shot network call | No | Yes | async\u002Fawait is simpler, no cancellable management |\n| Stream of values over time | Yes | AsyncStream | Combine's operators (debounce, combineLatest) are richer |\n| Debounce\u002Fthrottle user input | Yes | Awkward | Combine has built-in debounce\u002Fthrottle; AsyncStream requires manual implementation |\n| Merge multiple sources | Yes | TaskGroup | Combine's merge\u002FcombineLatest handle heterogeneous streams naturally |\n| Existing UIKit KVO\u002FNotification | Yes | Bridge | publisher(for:) and NotificationCenter.default.publisher are idiomatic Combine |\n| New project iOS 17+ | No | Yes | @Observable + async\u002Fawait is the modern pattern |\n| Existing codebase with Combine | Maintain | Migrate incrementally | Don't rewrite working pipelines — bridge at boundaries |\n\n### Quick Decision\n\n```\nIs it a one-shot operation (network call, file read)?\n├─ Yes → async\u002Fawait (simpler, no cancellable management)\n│\nDoes it need time-based operators (debounce, throttle, delay)?\n├─ Yes → Combine (built-in operators, no manual implementation)\n│\nAre you combining multiple ongoing streams?\n├─ Yes → Combine (combineLatest, merge, zip are purpose-built)\n│\nIs this new code on iOS 17+?\n├─ Yes → async\u002Fawait + @Observable (modern pattern)\n│\nIs it existing Combine code that works?\n└─ Yes → Keep it. Bridge at boundaries when async\u002Fawait code needs the data.\n```\n\n---\n\n## Part 2: Publisher\u002FSubscriber Lifecycle\n\n### AnyCancellable Storage Rules\n\nAnyCancellable cancels its subscription when deallocated. If you don't store it, the pipeline is cancelled immediately after setup.\n\n#### ❌ Pipeline dies instantly\n\n```swift\nfunc setupPipeline() {\n    publisher\n        .sink { value in\n            self.handle(value)  \u002F\u002F Never called\n        }\n    \u002F\u002F AnyCancellable returned by sink is discarded → subscription cancelled\n}\n```\n\n#### ✅ Store in Set\u003CAnyCancellable>\n\n```swift\nprivate var cancellables = Set\u003CAnyCancellable>()\n\nfunc setupPipeline() {\n    publisher\n        .sink { [weak self] value in\n            self?.handle(value)\n        }\n        .store(in: &cancellables)\n}\n```\n\n### Why Set, Not Array\n\n`Set\u003CAnyCancellable>` is the idiomatic choice because:\n- `store(in:)` works with both `Set` and `RangeReplaceableCollection` (including `Array`), but `Set` is conventional\n- Order doesn't matter for subscriptions\n- Prevents accidental duplicates if setup runs twice\n\n### 4 Memory Leak Patterns\n\n#### Leak 1: Strong self in sink\n\n```swift\n\u002F\u002F ❌ LEAK: sink closure captures self strongly\npublisher\n    .sink { value in\n        self.handle(value)  \u002F\u002F Strong capture → retain cycle\n    }\n    .store(in: &cancellables)\n\n\u002F\u002F ✅ FIX: weak self\npublisher\n    .sink { [weak self] value in\n        self?.handle(value)\n    }\n    .store(in: &cancellables)\n```\n\n#### Leak 2: Missing store(in:)\n\n```swift\n\u002F\u002F ❌ LEAK: cancellable assigned to local var, not stored\nlet cancellable = publisher.sink { handle($0) }\n\u002F\u002F cancellable deallocated at end of scope → pipeline cancelled\n\n\u002F\u002F ✅ FIX: store in instance property\npublisher.sink { [weak self] in self?.handle($0) }\n    .store(in: &cancellables)\n```\n\n#### Leak 3: Over-retained cancellables\n\n```swift\n\u002F\u002F ❌ LEAK: cancellables set never cleared, old pipelines accumulate\nfunc refreshData() {\n    \u002F\u002F Each call adds another subscription without removing the previous one\n    dataPublisher\n        .sink { [weak self] in self?.update($0) }\n        .store(in: &cancellables)\n}\n\n\u002F\u002F ✅ FIX: clear before re-subscribing\nfunc refreshData() {\n    cancellables.removeAll()  \u002F\u002F Cancel previous subscriptions\n    dataPublisher\n        .sink { [weak self] in self?.update($0) }\n        .store(in: &cancellables)\n}\n```\n\n#### Leak 4: assign(to:on:) strong capture\n\n`assign(to:on:)` captures the `on:` parameter **strongly**. When the target is `self`, you get a retain cycle: `self → cancellables → subscription → self`.\n\n```swift\n\u002F\u002F ❌ LEAK: assign(to:on:) retains self strongly — deinit never called\nuserPublisher\n    .map { $0.name }\n    .assign(to: \\.displayName, on: self)\n    .store(in: &cancellables)\n\n\u002F\u002F ✅ FIX: use assign(to:) with @Published projected value (iOS 14+)\nuserPublisher\n    .map { $0.name }\n    .assign(to: &$displayName)\n\u002F\u002F No store(in:) needed — subscription tied to @Published property lifetime\n```\n\nKey difference: `assign(to: &$prop)` does NOT return an `AnyCancellable` — the subscription is managed internally and cancelled when the `@Published` property's owner deallocates. No retain cycle, no cancellable storage needed.\n\nIf you must support iOS 13, use `sink` with `[weak self]` instead.\n\n---\n\n## Part 3: Essential Operators\n\nOne canonical example per group. These cover 90% of real-world usage.\n\n### Transform\n\n```swift\n\u002F\u002F map: transform each value\npublisher.map { $0.name }\n\n\u002F\u002F compactMap: transform + filter nil\npublisher.compactMap { Int($0) }\n\n\u002F\u002F flatMap: one-to-many (each value produces a new publisher)\nsearchText\n    .flatMap { query in\n        api.search(query)  \u002F\u002F Returns a publisher\n    }\n```\n\n**flatMap gotcha**: Without `.switchToLatest()` or `maxPublishers: .max(1)`, flatMap creates a new inner publisher for every upstream value. For search-as-you-type, use `map` + `switchToLatest` instead:\n\n```swift\nsearchText\n    .map { query in api.search(query) }\n    .switchToLatest()  \u002F\u002F Cancels previous search when new query arrives\n```\n\n### Combine Multiple Sources\n\n```swift\n\u002F\u002F combineLatest: latest value from each, fires when ANY changes\nPublishers.CombineLatest(namePublisher, agePublisher)\n    .map { name, age in \"\\(name), \\(age)\" }\n\n\u002F\u002F merge: interleave values from same-type publishers\nPublishers.Merge(localUpdates, remoteUpdates)\n    .sink { update in handle(update) }\n\n\u002F\u002F zip: pairs values 1:1 (waits for both to produce)\nPublishers.Zip(requestA, requestB)\n    .sink { responseA, responseB in \u002F* both complete *\u002F }\n```\n\n| Operator | Fires When | Use Case |\n|----------|-----------|----------|\n| combineLatest | Any input changes | Form validation (all fields) |\n| merge | Any input produces | Combining event streams |\n| zip | All inputs produce one value | Parallel requests that must complete together |\n\n### Time-Based\n\n```swift\n\u002F\u002F debounce: wait until values stop arriving (search-as-you-type)\nsearchTextPublisher\n    .debounce(for: .milliseconds(300), scheduler: RunLoop.main)\n    .sink { [weak self] query in self?.search(query) }\n    .store(in: &cancellables)\n\n\u002F\u002F throttle: emit at most once per interval (scroll position)\nscrollOffsetPublisher\n    .throttle(for: .milliseconds(100), scheduler: RunLoop.main, latest: true)\n    .sink { [weak self] offset in self?.updateHeader(offset) }\n    .store(in: &cancellables)\n```\n\n| Operator | Behavior | Use Case |\n|----------|----------|----------|\n| debounce | Waits for silence, then emits last value | Search fields, auto-save |\n| throttle(latest: true) | Emits latest value at fixed intervals | Scroll tracking, sensor data |\n| throttle(latest: false) | Emits first value at fixed intervals | Rate-limiting button taps |\n\n### Error Handling\n\n```swift\n\u002F\u002F tryMap: transform that can throw\npublisher.tryMap { data in\n    try JSONDecoder().decode(Model.self, from: data)\n}\n\n\u002F\u002F mapError: convert error types\npublisher.mapError { error in\n    AppError.network(error)\n}\n\n\u002F\u002F replaceError: provide fallback value (terminates error path)\npublisher.replaceError(with: defaultValue)\n\n\u002F\u002F retry: re-subscribe on failure\npublisher.retry(3)  \u002F\u002F Retry up to 3 times before propagating error\n```\n\n**Error handling order matters**: `retry` should come before `replaceError`. Retry re-subscribes to the upstream publisher; replaceError terminates the error and makes the pipeline infallible.\n\n```swift\napi.fetchData()\n    .retry(3)                    \u002F\u002F Try 3 more times on failure\n    .replaceError(with: cached)  \u002F\u002F If all retries fail, use cache\n    .sink { data in update(data) }\n    .store(in: &cancellables)\n```\n\n**replaceError after flatMap kills the outer pipeline**: If `replaceError` is downstream of `flatMap`, a single inner publisher error terminates the entire pipeline — not just that one request. Move error handling inside `flatMap` so each inner publisher handles its own errors:\n\n```swift\n\u002F\u002F ❌ One API error kills the entire pipeline\n$searchText\n    .flatMap { query in api.search(query) }\n    .replaceError(with: [])  \u002F\u002F Pipeline completes on first error\n    .sink { ... }\n\n\u002F\u002F ✅ Each search handles its own errors independently\n$searchText\n    .flatMap { query in\n        api.search(query)\n            .replaceError(with: [])  \u002F\u002F Only this search affected\n    }\n    .sink { ... }\n```\n\n---\n\n## Part 4: @Published + ObservableObject\n\n### willSet Timing\n\n`@Published` fires its publisher in `willSet`, not `didSet`. This means subscribers see the new value before the property has actually been set on the object.\n\n```swift\nclass ViewModel: ObservableObject {\n    @Published var count = 0\n\n    init() {\n        $count.sink { newValue in\n            \u002F\u002F 'newValue' is the incoming value\n            \u002F\u002F BUT self.count is still the OLD value here\n            print(\"New: \\(newValue), Current: \\(self.count)\")\n            \u002F\u002F Prints \"New: 1, Current: 0\" when count is set to 1\n        }\n        .store(in: &cancellables)\n    }\n}\n```\n\nIf you need to read the property's value after it's been set, don't subscribe to `$count` — use a `didSet` observer instead, or read `self.count` after a brief deferral. The `$` publisher is designed for reacting to the incoming value, not for reading post-mutation state.\n\n### Nested ObservableObject Trap\n\nSwiftUI does NOT observe nested ObservableObject changes. Only the top-level object's `objectWillChange` triggers view updates.\n\n```swift\n\u002F\u002F ❌ View won't update when settings.theme changes\nclass AppState: ObservableObject {\n    @Published var settings = Settings()  \u002F\u002F Settings is also ObservableObject\n}\n\nclass Settings: ObservableObject {\n    @Published var theme = \"light\"  \u002F\u002F Changes here don't propagate\n}\n\n\u002F\u002F ✅ FIX: Forward objectWillChange manually\nclass AppState: ObservableObject {\n    @Published var settings = Settings()\n    private var cancellables = Set\u003CAnyCancellable>()\n\n    init() {\n        settings.objectWillChange\n            .sink { [weak self] _ in\n                self?.objectWillChange.send()\n            }\n            .store(in: &cancellables)\n    }\n}\n```\n\n**Better fix for iOS 17+**: Migrate to `@Observable`, which handles nested observation automatically. See `axiom-swift-concurrency` for migration patterns.\n\n### Thread Safety Warning\n\n`@Published` is NOT thread-safe. Setting a `@Published` property from a background thread triggers `objectWillChange` off the main thread, which can crash SwiftUI views.\n\n```swift\n\u002F\u002F ❌ CRASH: @Published set from background thread\nclass ViewModel: ObservableObject {\n    @Published var data: [Item] = []\n\n    func fetch() {\n        Task {\n            let items = await api.fetchItems()\n            data = items  \u002F\u002F Background thread → crash\n        }\n    }\n}\n\n\u002F\u002F ✅ FIX: Ensure main thread\n@MainActor\nclass ViewModel: ObservableObject {\n    @Published var data: [Item] = []\n\n    func fetch() {\n        Task {\n            let items = await api.fetchItems()\n            data = items  \u002F\u002F Safe — @MainActor ensures main thread\n        }\n    }\n}\n```\n\n---\n\n## Part 5: Bridging Combine and async\u002Fawait\n\n### Publisher → AsyncSequence\n\nUse `.values` to consume any publisher as an async sequence:\n\n```swift\nlet cancellable = notificationPublisher\n    .sink { notification in handle(notification) }\n\n\u002F\u002F ✅ Modern equivalent using .values\nfor await notification in notificationPublisher.values {\n    handle(notification)\n}\n```\n\n**Caveats with `.values`**:\n- The `for await` loop runs indefinitely until the publisher completes or the Task is cancelled\n- Errors thrown by the publisher terminate the loop\n- Only one consumer — if two `for await` loops consume the same `.values`, behavior is undefined\n\n### async\u002Fawait → Publisher\n\nWrap an async function in `Future` for Combine consumption:\n\n```swift\nfunc fetchUser(id: String) async throws -> User { ... }\n\n\u002F\u002F Wrap as a Combine publisher\nlet userPublisher = Future\u003CUser, Error> { promise in\n    Task {\n        do {\n            let user = try await fetchUser(id: \"123\")\n            promise(.success(user))\n        } catch {\n            promise(.failure(error))\n        }\n    }\n}\n```\n\n**Future executes immediately** — it runs its closure when created, not when subscribed. Wrap in `Deferred` if you need lazy execution:\n\n```swift\nlet lazyPublisher = Deferred {\n    Future\u003CUser, Error> { promise in\n        Task {\n            do {\n                let user = try await fetchUser(id: \"123\")\n                promise(.success(user))\n            } catch {\n                promise(.failure(error))\n            }\n        }\n    }\n}\n```\n\n### Gradual Migration Strategy\n\nDon't rewrite working Combine code. Bridge at the boundary:\n\n```\nCombine pipeline  →  .values  →  async\u002Fawait code\n                     (bridge)\n\nasync function    →  Future   →  Combine pipeline\n                     (bridge)\n```\n\n**Migration priority**:\n1. New code: write in async\u002Fawait\n2. Boundary: bridge with `.values` or `Future`\n3. Existing Combine: leave working pipelines alone\n4. Rewrite: only when the pipeline needs significant changes anyway\n\n---\n\n## Part 6: Subjects\n\n### PassthroughSubject vs CurrentValueSubject\n\n| Feature | PassthroughSubject | CurrentValueSubject |\n|---------|-------------------|-------------------|\n| Initial value | None | Required |\n| Late subscribers | Miss previous values | Get current value immediately |\n| `.value` property | No | Yes (read current value) |\n| Use case | Events (button taps, notifications) | State (current selection, loading status) |\n\n```swift\n\u002F\u002F Event-driven: no initial value, late subscribers miss past events\nlet taps = PassthroughSubject\u003CVoid, Never>()\ntaps.send()\n\n\u002F\u002F State-driven: always has a current value\nlet isLoading = CurrentValueSubject\u003CBool, Never>(false)\nisLoading.value = true  \u002F\u002F Direct access\nisLoading.send(false)   \u002F\u002F Also works\n```\n\n### Send-After-Completion Pitfall\n\nOnce a Subject receives a completion event, all subsequent `send()` calls are silently ignored. No crash, no error — just silence.\n\n```swift\nlet subject = PassthroughSubject\u003CInt, Never>()\n\nsubject.send(1)           \u002F\u002F Delivered\nsubject.send(completion: .finished)\nsubject.send(2)           \u002F\u002F Silently ignored — no crash, no warning\n\n\u002F\u002F This is the most common cause of \"my pipeline stopped working\"\n```\n\n**Diagnosis**: If a pipeline silently stops producing values, check whether anything upstream sent a `.finished` or `.failure` completion. Once complete, the pipeline is dead.\n\n---\n\n## Part 7: Cold vs Hot Publishers (share\u002Fmulticast)\n\nMost Combine publishers are **cold** — they start work when subscribed and each subscriber gets its own independent execution. `URLSession.dataTaskPublisher` fires a new HTTP request per subscriber.\n\n```swift\n\u002F\u002F ❌ Two subscribers = two network requests\nlet publisher = URLSession.shared\n    .dataTaskPublisher(for: url)\n    .map(\\.data)\n    .eraseToAnyPublisher()\n\npublisher.sink { cache.store($0) }.store(in: &cancellables)  \u002F\u002F Request 1\npublisher.sink { display($0) }.store(in: &cancellables)       \u002F\u002F Request 2\n```\n\n### share()\n\n`.share()` makes a cold publisher hot — the first subscriber triggers the work, subsequent subscribers share the output:\n\n```swift\n\u002F\u002F ✅ One request, shared result\nlet publisher = URLSession.shared\n    .dataTaskPublisher(for: url)\n    .map(\\.data)\n    .share()\n    .eraseToAnyPublisher()\n\npublisher.sink { cache.store($0) }.store(in: &cancellables)  \u002F\u002F Triggers request\npublisher.sink { display($0) }.store(in: &cancellables)       \u002F\u002F Shares result\n```\n\n### share() Gotchas\n\n| Gotcha | Effect | Fix |\n|--------|--------|-----|\n| Late subscribers miss values | `share()` uses PassthroughSubject — no replay | Attach all subscribers before the first value arrives, or use `multicast` with `CurrentValueSubject` |\n| Upstream completed before subscriber attaches | Late subscriber immediately gets `.finished` with no values | Ensure subscription order, or cache the result outside Combine |\n| All subscribers cancel → upstream cancels | New subscriber after that triggers a NEW upstream execution | Expected behavior, but surprising if you assumed the result was cached |\n\n### When to use share()\n\n```\nMultiple subscribers to the same expensive publisher?\n├─ No → Don't use share() (unnecessary complexity)\n│\n├─ Yes, all subscribe at the same time?\n│   └─ Yes → share() works\n│\n└─ Yes, subscribers attach at different times?\n    └─ Use multicast(subject:) with CurrentValueSubject, or cache the result in a property\n```\n\n---\n\n## Anti-Rationalization\n\n| Thought | Reality |\n|---------|---------|\n| \"Combine is dead, just use async\u002Fawait\" | Combine has no deprecation notice. Thousands of production apps use it. Rewriting working pipelines wastes time and introduces bugs. Bridge incrementally instead. |\n| \"I'll just use .sink everywhere\" | Without `[weak self]` and proper `store(in:)`, every sink is a potential memory leak. The lifecycle rules in Part 2 prevent the top 4 leak patterns. |\n| \"assign(to:on:) is fine, it's the standard API\" | It captures `on:` strongly — retain cycle if target is `self`. Use `assign(to: &$prop)` instead (Part 2, Leak 4). |\n| \"debounce and throttle are the same thing\" | debounce waits for silence; throttle emits at intervals. Using the wrong one causes either delayed responses or missed events. Part 3 has the decision table. |\n| \"I know how @Published works\" | @Published fires on willSet, not didSet. Nested ObservableObject doesn't propagate. Background thread access crashes. Part 4 covers all three traps. |\n| \"I'll migrate everything to async\u002Fawait at once\" | Full rewrites of working Combine code introduce bugs and waste time. Bridge at boundaries (Part 5). Rewrite only when the pipeline needs significant changes anyway. |\n\n---\n\n## Pressure Scenarios\n\n### Scenario 1: \"Let's migrate all Combine code to async\u002Fawait\"\n\n**Setup**: Tech lead wants to modernize the codebase. \"Combine is legacy, let's rip it out.\"\n\n**Pressure**: Authority + scope creep. The entire data layer uses Combine publishers, @Published properties, and operator chains.\n\n**Expected with skill**: Push back with the gradual migration strategy (Part 5). New code uses async\u002Fawait. Boundaries use `.values` and `Future`. Existing working pipelines stay until they need changes. Full rewrite is the most expensive option with the least benefit.\n\n**Pushback template**: \"Combine isn't deprecated — Apple still ships it in every SDK. A full rewrite of working pipelines introduces bugs we don't have today. Let's bridge at boundaries: new code in async\u002Fawait, `.values` to consume existing publishers, and we only rewrite a pipeline when we're already changing it significantly.\"\n\n---\n\n### Scenario 2: \"Pipeline silently stopped — just recreate it\"\n\n**Setup**: A Combine pipeline stopped producing values after a refactor. No crash, no error.\n\n**Pressure**: Time pressure. \"Just tear it down and rebuild.\"\n\n**Expected with skill**: Diagnose before rebuilding. Check: (1) Was a completion sent upstream? (send-after-completion, Part 6). (2) Is the AnyCancellable still alive? (storage rules, Part 2). (3) Did the publisher error without handling? (replaceError \u002F catch, Part 3). These three causes cover 90% of silent pipeline failures.\n\n**Diagnostic checklist**:\n1. Is the `AnyCancellable` still stored? (Set not cleared, not deallocated)\n2. Did anything upstream send `.finished` or `.failure`?\n3. Is there a `tryMap` or other throwing operator without error handling?\n4. Was `switchToLatest` used where the outer publisher completed?\n\n**Pushback template**: \"Before rebuilding, let me check four things: cancellable lifecycle, upstream completions, unhandled errors, and switchToLatest completion. One of these is almost always the cause. It takes 5 minutes to diagnose vs 30 minutes to rebuild and test.\"\n\n---\n\n### Scenario 3: \"Settings changes aren't updating the UI\"\n\n**Setup**: A settings screen uses a nested ObservableObject. The parent `AppState` holds a `Settings` object. When the user changes `settings.theme`, the UI doesn't update.\n\n**Pressure**: \"The binding works in isolation, it must be a SwiftUI bug. Let me just force a refresh with objectWillChange.send().\"\n\n**Expected with skill**: Recognize the nested ObservableObject trap (Part 4). SwiftUI does NOT observe nested ObservableObject changes — only the top-level object's `objectWillChange` triggers view updates. The fix is either forwarding `objectWillChange` from the nested object, or migrating to `@Observable` (iOS 17+) which handles nesting automatically.\n\n**Anti-pattern without skill**: Sprinkling `objectWillChange.send()` calls throughout the code, adding `@Published` to every nested property (which doesn't help), or restructuring the model to flatten everything into one object (losing separation of concerns).\n\n**Pushback template**: \"SwiftUI only observes the top-level ObservableObject. Nested objects need their objectWillChange forwarded to the parent. Part 4 has the exact pattern — it's a 5-line fix in the parent's init, not a SwiftUI bug.\"\n\n---\n\n## Resources\n\n**WWDC**: 2019-722, 2019-721, 2020-10034\n\n**Docs**: \u002Fcombine, \u002Fcombine\u002Fanycancellable, \u002Fcombine\u002Fpublished\n\n**Skills**: swift-concurrency, memory-debugging\n\n",{"name":5,"license":15,"metadata":38,"description":7},{"version":39,"last-updated":40},"1.0.0","2026-03-12","main","def8531e65114c0fca8fb8551c1871ee0eed705c","skills\u002FCharlesWiltgen\u002FAxiom\u002Faxiom-combine-patterns",24,"https:\u002F\u002Fgithub.com\u002FComeOnOliver\u002Fskillshub","https:\u002F\u002Fskillshub.wtf","https:\u002F\u002Fgithub.com\u002FComeOnOliver","AI & Blockchain Engineer\r\n","2026-06-24 22:07:19",{"source":8,"skillName":5,"commands":51,"prompt":61,"zipAvailable":62},[52,55,58],{"tool":53,"command":54},"npx","npx skills add ComeOnOliver\u002Fskillshub --skill axiom-combine-patterns",{"tool":56,"command":57},"bunx","bunx skills add ComeOnOliver\u002Fskillshub --skill axiom-combine-patterns",{"tool":59,"command":60},"pnpm","pnpm dlx skills add ComeOnOliver\u002Fskillshub --skill axiom-combine-patterns","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002FComeOnOliver\u002Fskillshub\u002Fblob\u002Fmain\u002Fskills\u002FCharlesWiltgen\u002FAxiom\u002Faxiom-combine-patterns\u002FSKILL.md",true,[],[65,74,83,92,98,104],{"skillNo":66,"name":67,"nameZh":6,"description":6,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":68,"categories":69,"keywords":70,"publishedAt":33},"01M6FKJN13GMG4KY57J3QD8GY5","model-hierarchy-skill","https:\u002F\u002Fgithub.com\u002FComeOnOliver\u002Fskillshub\u002Fblob\u002Fmain\u002Fskills\u002Fzscole\u002Fmodel-hierarchy-skill\u002Fmodel-hierarchy-skill\u002FSKILL.md",[],[71,72,73],"model","model hierarchy","model hierarchy skill",{"skillNo":75,"name":76,"nameZh":6,"description":6,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":77,"categories":78,"keywords":79,"publishedAt":33},"01M6FKJJJ6GCAMR4PPPRD12M5X","zoom-mcp","https:\u002F\u002Fgithub.com\u002FComeOnOliver\u002Fskillshub\u002Fblob\u002Fmain\u002Fskills\u002Fzoom\u002Fskills\u002Fzoom-mcp\u002FSKILL.md",[],[80,81,82],"MCP","zoom","zoom mcp",{"skillNo":84,"name":85,"nameZh":6,"description":6,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":86,"categories":87,"keywords":88,"publishedAt":33},"01M6FKJE3KYT3KPEZMEEHYKA6K","zoom-apps-sdk","https:\u002F\u002Fgithub.com\u002FComeOnOliver\u002Fskillshub\u002Fblob\u002Fmain\u002Fskills\u002Fzoom\u002Fskills\u002Fzoom-apps-sdk\u002FSKILL.md",[],[89,90,91,81],"sdk","zoom apps sdk","apps",{"skillNo":93,"name":94,"nameZh":6,"description":6,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":95,"categories":96,"keywords":97,"publishedAt":33},"01M6FKJ9EDH9Q5VWDF8HAJRSP0","windows","https:\u002F\u002Fgithub.com\u002FComeOnOliver\u002Fskillshub\u002Fblob\u002Fmain\u002Fskills\u002Fzoom\u002Fskills\u002Fwindows\u002FSKILL.md",[],[94],{"skillNo":99,"name":100,"nameZh":6,"description":6,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":101,"categories":102,"keywords":103,"publishedAt":33},"01M6FKJ666BEEFC3AE9GJ72Q93","whiteboard","https:\u002F\u002Fgithub.com\u002FComeOnOliver\u002Fskillshub\u002Fblob\u002Fmain\u002Fskills\u002Fzoom\u002Fskills\u002Fwhiteboard\u002FSKILL.md",[],[100],{"skillNo":105,"name":106,"nameZh":6,"description":6,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":107,"categories":108,"keywords":109,"publishedAt":33},"01M6FKJ21WFCDGTJQ2Q91T9DVW","websockets","https:\u002F\u002Fgithub.com\u002FComeOnOliver\u002Fskillshub\u002Fblob\u002Fmain\u002Fskills\u002Fzoom\u002Fskills\u002Fwebsockets\u002FSKILL.md",[],[106]]