Publishers, operators and subscriptions
Think of a pipeline as a water pipe with filters. The publisherPublisher (Combine)A Combine type that emits values over time, then finishes or fails, to subscribers that request them.Open in glossary → is the tap: it sends values. Operators are filters along the pipe: change each value (map), drop some (filter), wait for a pause (debounce). The subscriber at the end is the glass: sink runs a closure for each value that arrives.
A publisher can send any number of values, and then it may end: either it finishes normally or it fails with an error. After that, nothing more comes through.
One rule surprises everyone at first: sink returns an AnyCancellable, a ticket for the subscription. When the ticket is thrown away, the subscription is cancelled. So you keep it, usually in a Set<AnyCancellable> on the object.
A Publisher has Output and Failure types and emits zero or more values followed by at most one completion (.finished or .failure). Subscribers request demand (sink and assign request .unlimited), which is how Combine models backpressure. Most publishers are cold (each subscription starts its own work: two subscribers to a dataTaskPublisher make two requests; share() or multicast makes it hot), while subjects (PassthroughSubject, CurrentValueSubject) and @Published are hot. @Published emits in willSet, before the property changes. A completed stream never emits again, which is why errors must be handled inside flatMap/map+switchToLatest rather than at the end of a long-lived pipeline. Threading: operators run on whatever thread the upstream emits on; receive(on:) moves downstream delivery, subscribe(on:) moves subscription and upstream work.
import Combine
@MainActor
final class SearchViewModel: ObservableObject {
@Published var query = ""
@Published private(set) var results: [Product] = []
private var cancellables = Set<AnyCancellable>()
init(api: ProductAPI) {
$query
.map { $0.trimmingCharacters(in: .whitespaces) }
.removeDuplicates() // "sh", "sh" → one request
.debounce(for: .milliseconds(300), scheduler: RunLoop.main) // wait for a pause in typing
.filter { $0.count >= 2 }
.map { query in
api.search(query) // AnyPublisher<[Product], Error>
.replaceError(with: []) // handle errors per request
}
.switchToLatest() // only the newest query's results
.receive(on: DispatchQueue.main)
.assign(to: &$results) // lives as long as self, no cycle
}
}
struct ProductAPI {
func search(_ query: String) -> AnyPublisher<[Product], Error> {
var components = URLComponents(string: "https://api.example.com/search")!
components.queryItems = [URLQueryItem(name: "q", value: query)]
return URLSession.shared.dataTaskPublisher(for: components.url!)
.map(\.data)
.decode(type: [Product].self, decoder: JSONDecoder())
.eraseToAnyPublisher()
}
}Reading it top to bottom:
$querysends the text every time the user types.removeDuplicatesskips a value equal to the previous one;debouncewaits until typing pauses for 300 ms;filterignores one-letter queries.mapturns each query into a network request (itself a publisher). If the request fails,replaceErrorturns the error into an empty list, for that one request only.switchToLatestlistens only to the newest request, so results for an old query can’t overwrite newer ones.assign(to: &$results)writes each result intoresults. This form manages its own subscription, so noAnyCancellableis needed here.
Tap the line with the bug.
final class ClockViewModel: ObservableObject {
@Published var now = Date()
func start() {
Timer.publish(every: 1, on: .main, in: .common)
.autoconnect()
.sink { [weak self] date in
self?.now = date
}
}
}Hint: What does sink return, and what happens to it here?
sink returns an AnyCancellable, and nothing keeps it: it’s deallocated at the end of start(), which cancels the subscription immediately. The clock never updates. (The compiler even warns: “result of call to ‘sink’ is unused”.)
Store it for as long as the subscription should live:
private var cancellables = Set<AnyCancellable>()
func start() {
Timer.publish(every: 1, on: .main, in: .common)
.autoconnect()
.sink { [weak self] date in self?.now = date }
.store(in: &cancellables)
}Predict the output
A view model has @Published var count = 0, and in init: $count.sink { [weak self] value in print(value, self?.count ?? -1) }.store(in: &cancellables). Then count = 5 runs. What is printed after "0 0" from the subscription?
@Published sends the new value before the property is updated (in willSet). Inside the closure, value is 5 but self.count is still 0. Use the value the publisher gives you, not the property. (The first line, 0 0, comes from @Published sending the current value on subscription.)
Practice: a form that enables its button
combineLatest joins publishers: it emits whenever any of them changes, with the latest value of each. That’s perfect for form validation.
final class SignUpViewModel: ObservableObject {
@Published var email = ""
@Published var password = ""
@Published private(set) var canSubmit = false
init() {
$email.combineLatest($password)
.map { email, password in
email.contains("@") && password.count >= 8
}
.removeDuplicates()
.assign(to: &$canSubmit)
}
}Show a loading indicator
Add @Published private(set) var isLoading = false to the search view model: true while a request is running, false when its results (or the error) arrive.
›
handleEvents(receiveOutput:) runs a side effect when a value passes through, without changing it. Where in the pipeline does a request start?
SolutionTry it yourself first
Set it to true when a query passes the filter, and back to false when results arrive:
$query
.map { $0.trimmingCharacters(in: .whitespaces) }
.removeDuplicates()
.debounce(for: .milliseconds(300), scheduler: RunLoop.main)
.filter { $0.count >= 2 }
.handleEvents(receiveOutput: { [weak self] _ in self?.isLoading = true })
.map { api.search($0).replaceError(with: []) }
.switchToLatest()
.receive(on: DispatchQueue.main)
.sink { [weak self] products in
self?.isLoading = false
self?.results = products
}
.store(in: &cancellables)sink replaces assign here because two properties change; [weak self] avoids a cycle, since self stores the subscription.
Operators interviewers ask about
| Operator | Behavior |
|---|---|
flatMap | Subscribes to every inner publisher; results from all of them interleave (bounded by maxPublishers). |
map + switchToLatest | Cancels the previous inner publisher when a new one arrives. Right for search. |
combineLatest | Emits the latest of each once all have emitted; on any change. |
zip | Pairs values by index; waits for both. |
merge | Interleaves same-typed publishers. |
debounce / throttle | Emit after a quiet period / at most once per interval. |
share() | One upstream subscription for many subscribers (hot). |
catch / replaceError | Replace a failure with another publisher / value; the upstream is still finished. |
assign(to: \.results, on: self) retains self strongly through the returned AnyCancellable; stored in self.cancellables, that’s a retain cycle. assign(to: &$results) (iOS 14+) ties the subscription to the @Published property instead and has no cycle.
- Publisher → operators → subscriber; values then at most one completion. Demand-based backpressure;
sink/assignrequest unlimited. AnyCancellableowns the subscription: dropped = cancelled. Store it (store(in:)) or useassign(to: &$prop).- Cold vs hot:
dataTaskPublisherper subscriber;share()to multicast.@Publishedemits in willSet. - Search:
removeDuplicates→debounce→map { request.catch… }→switchToLatest→receive(on: main). flatMapinterleaves all inner results;switchToLatestcancels the old one.assign(to:on: self)retains self.
Check this part
A sink’s AnyCancellable isn’t stored anywhere. What happens?
What does debounce(for: .milliseconds(300)) do to a stream of keystrokes?
Search uses flatMap for requests. A slow request for "sw" returns after the one for "swift". What does the user see?
Which subscription creates a retain cycle when stored in self.cancellables?