Files
2nd/10_Wiki/Topic_Programming/Coding/iOS_Combine_Patterns.md
T
Antigravity Agent 9148c358d0 docs(10_Wiki): 위키 전체 재구성 — Topic_* 폴더를 4개 카테고리로 통합 + 대규모 중복 제거
Topic_Agent/Topic_Blog/Topics/Topics_Biz/Topics_Meeting/Topics_Rag의 마크다운 지식 문서를
Topic_General/Topic_Programming/Topic_Graphic/Topic_Business 4개 카테고리로 재분류.

- 중복 제거: frontmatter의 status:duplicate/merged + duplicate_of/redirect_to 필드로
  자기 자신을 중복으로 선언한 리다이렉트 stub 1032개 제거, 완전 동일 내용 파일 472개 제거,
  동일 파일명·다른 내용 충돌 시 더 큰(완전한) 버전만 유지(162개 제거) — 총 1639개 중복 제거.
- 분류: 폴더 단위로 명확한 항목(AI_and_ML/Coding/Architecture 등 → Programming,
  Comfyui/Visual_Effects → Graphic, Topics_Biz/Topics_Meeting/사업 등 → Business,
  Poetic_Blog_Writing/창의성/Game_Design 등 → General)은 폴더 우선순위로,
  나머지 혼재 폴더(Topic_Agent/Topic_Blog/Topics 루트/Thinking & Reasoning/Other/UI_UX_Assets)는
  title/tags 키워드 스코어링으로 파일 단위 분류(불명확한 경우 General로 폴백).
  원본 폴더명은 "From_*" 서브폴더로 보존해 추적 가능성 유지.
- 최종 배치: Programming 2784 / General 1608 / Graphic 285 / Business 249 = 4926개 문서.
- 에이전트 운영 상태(.astra/.agent/.obsidian/sessions/memory/_company/docs/lessons/_shared/src)는
  지식 콘텐츠가 아니므로 재분류 대상에서 제외하고 원위치 유지.
- Topics/Topic_email(상위 보호 폴더 Topic_email과 파일명 100% 중복) 삭제 — 보호 폴더 자체는 미변경.
- 완전히 비게 된 Topic_Agent/Topic_Blog/Topics_Biz/Topics_Rag 폴더 제거.
2026-07-05 00:33:48 +09:00

3.4 KiB

id, title, category, status, source_trust_level, verification_status, created_at, updated_at, tags, tech_stack, applied_in, aliases
id title category status source_trust_level verification_status created_at updated_at tags tech_stack applied_in aliases
ios-combine-patterns Combine — 비동기 stream / 변환 / cancel Coding draft B conceptual 2026-05-09 2026-05-09
ios
combine
swift
async
vibe-coding
language applicable_to
Swift / Combine
iOS 13+
Publisher
Subscriber
AnyCancellable
sink

Combine — 비동기 stream

Apple 의 reactive framework. async/await 가 더 단순하지만, Combine 은 변환 체인 / 동시 source 결합 / 자동 cancel 에서 강함. SwiftUI 와 자연스럽게 통합.

📖 핵심 개념

  • Publisher: 값 stream emit.
  • Subscriber: 값 받기.
  • Operator: map / filter / debounce / combineLatest / merge.
  • AnyCancellable: subscription handle. dispose 시 자동 cancel.

💻 코드 패턴

Search debounce (typical)

import Combine

final class SearchViewModel: ObservableObject {
    @Published var query: String = ""
    @Published var results: [Item] = []
    private var bag = Set<AnyCancellable>()

    init() {
        $query
            .debounce(for: .milliseconds(300), scheduler: DispatchQueue.main)
            .removeDuplicates()
            .filter { $0.count >= 2 }
            .map { q in
                URLSession.shared.dataTaskPublisher(for: searchURL(q))
                    .map(\.data)
                    .decode(type: [Item].self, decoder: JSONDecoder())
                    .replaceError(with: [])
            }
            .switchToLatest() // 이전 검색 cancel
            .receive(on: DispatchQueue.main)
            .assign(to: &$results)
    }
}

combineLatest

Publishers.CombineLatest3($email, $password, $agreedToTerms)
    .map { e, p, a in e.contains("@") && p.count >= 8 && a }
    .assign(to: &$canSubmit)

Cancel

let task = publisher.sink(receiveValue: { ... })
// 화면 disappear
task.cancel()
// 또는 bag.removeAll()

async/await 와 통합

let value = try await publisher.values.first { _ in true }!

// Or convert async to publisher
extension Publisher {
    func toAsync() async throws -> Output { ... }
}

NotificationCenter — Combine

NotificationCenter.default.publisher(for: UIApplication.didBecomeActiveNotification)
    .sink { _ in self.refresh() }
    .store(in: &bag)

🤔 의사결정 기준

상황 Combine async/await
한 번 호출
Stream of values (search, websocket) AsyncSequence
여러 source 결합 — combineLatest 직접 await
SwiftUI @Published / assign manual setState
iOS 13 호환성 iOS 15+
Time-based (debounce, throttle) 직접 구현

안티패턴

  • AnyCancellable 무시: _ = publisher.sink(...) — 즉시 deallocate. store(in: &bag).
  • 메인 스레드에서 무거운 변환: receive(on: DispatchQueue.global()) 으로 분기.
  • switchToLatest 안 씀: 검색 결과 race. 이전 결과가 새 결과 덮어씀.
  • assign 후 weak self 안 함: cycle. assign(to: &$x) 또는 sink + [weak self].
  • error 처리 누락: .sink 의 receiveCompletion 무시 → silent failure.
  • 모든 곳 Combine: async/await 가 더 단순한 경우 많음.

🤖 LLM 활용 힌트

  • 검색 / 스트림 / SwiftUI binding = Combine 적합.
  • 한 번 호출 = async/await.

🔗 관련 문서