11.7 · Operator behaviour, error placement, retry, flatMap limits and debugging
The first pass named the operators. This section covers how they behave in detail, which is where Combine interviews and production bugs live: which operator ends the stream, which one re-runs work, and where a catch belongs.
Mental model. Read each operator as what it emits, when it completes, and what it demands upstream. Errors are terminal; retry and catch change what “terminal” means.
Choosing and combining
A tour of everyday operators, and how flatMap limits its inner publishers.
- What do collect, prefix, dropFirst, drop(while:), scan, reduce, removeDuplicates, compactMap, output(in:), prepend and append emit, and which of them wait for completion?
Most operators are best remembered by what they do to the stream’s length and timing. prefix(3) passes the first three values then completes the stream early… - What does flatMap(maxPublishers:) do, and why can limiting it silently lose values?
flatMap subscribes to a new inner publisher for every upstream value, so with no limit a burst of values starts a burst of requests. maxPublishers: .max(n)…
Errors, retry and debugging
Where catch belongs, why retry needs a lazy publisher, and handleEvents.
- Where should a catch go in a search pipeline, and what happens to the stream if you put it outside the flatMap?
A failure is terminal: once a publisher fails, the stream is over. catch replaces the failed publisher with another one, and whatever it replaces is what ends.… - Why does retry sometimes not retry anything, and how do Future and Deferred differ here?
retry(n) works by re-subscribing to the same upstream publisher after a failure. If subscribing to it again does the work again, you get a real retry; if it… - How do you see what a Combine pipeline is doing: handleEvents, print, breakpoint and the order of subscription, request, output, completion and cancel?
Combine pipelines are hard to step through, so you instrument them. handleEvents lets you observe each lifecycle event without changing the stream…
More in Combine
- 11.1 · Publisher, Subscriber, Subscription and demand
- 11.2 · map, scan, combineLatest, flatMap, switchToLatest, debounce, share
- 11.3 · PassthroughSubject, CurrentValueSubject and @Published
- 11.4 · receive(on:), subscribe(on:) and where code runs
- 11.5 · AnyCancellable, subscription lifetime, and failure versus Never
- 11.6 · Combine versus async/await, and testing pipelines
- 11.8 · Future versus Deferred, subject replay, share, and bridging to async
- 11.9 · Which thread each stage runs on, schedulers, throttle versus debounce, and timers
- 11.10 · Cancelling and completing, the cycle that survives a deinit, and failure types