Combine and Reactive Programming

Concepts: Publisher, Subscriber, operators (map, filter, combineLatest, merge, zip, debounce, throttle, retry, catch), schedulers, AnyCancellable, Future, @Published.

Status: Combine is still supported, but for new code Apple favors Swift Concurrency (AsyncSequence, AsyncStream, swift-async-algorithms) and the Observation framework. Bridge them with publisher.values (Combine → AsyncSequence).

import Combine

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

    init(service: SearchService) {
        $query
            .debounce(for: .milliseconds(300), scheduler: RunLoop.main)
            .removeDuplicates()
            .filter { !$0.isEmpty }
            .flatMap { query in
                service.search(query).catch { _ in Just([]) }
            }
            .receive(on: DispatchQueue.main)
            .assign(to: &$results)
    }
}

let publisher = [1, 2, 3].publisher
    .map { $0 * 10 }
    .sink { print($0) }

let subject = PassthroughSubject<String, Never>()
let current = CurrentValueSubject<Int, Never>(0)