With Combine, how do debounce, removeDuplicates and receive(on:) shape an airport search field's queries, and which queue does each stage deliver on?
answer
- wait for the typing to pause
- the timer restarts on every value
- debounce delivers on its own scheduler
- skip a query equal to the last one
- hop to DispatchQueue.main before UI state
basics
~20 sdebounce(for:scheduler:) passes a value only after the field has been quiet for the interval, delivering on that scheduler; removeDuplicates() then drops a query equal to the previous one; receive(on:) moves later stages to a scheduler such as DispatchQueue.main.
solid answer
~40 sStart from the field's `@Published var query` and its `$query` publisher. `debounce(for: .milliseconds(300), scheduler: DispatchQueue.main)` holds each value and restarts the wait on every keystroke, so only the text present when typing pauses goes through, delivered on that scheduler. `removeDuplicates()` then drops a value equal to the last one it passed, so typing 'lon', a fourth letter and a backspace does not search 'lon' twice; after `debounce` it compares settled queries rather than keystrokes. Combine does not switch threads by itself: a stage runs on whatever thread its upstream emits on. If matching runs on a background queue, put `receive(on: DispatchQueue.main)` before the stage that writes UI state. `subscribe(on:)` would not help there, and `throttle(for:scheduler:latest:)` is the wrong operator, because it emits at a steady rate during typing instead of waiting for a pause.
code
swift · 21 linesimport Combine
import Foundation
final class AirportSuggestionsModel {
@Published var query = ""
@Published private(set) var suggestions: [String] = []
private let airports = ["LHR London Heathrow", "LGW London Gatwick", "LIS Lisbon"]
private let work = DispatchQueue(label: "airport-index")
init() {
$query
.debounce(for: .milliseconds(300), scheduler: DispatchQueue.main)
.removeDuplicates()
.receive(on: work) // match off the main queue
.map { [airports] text in
text.count < 2 ? [] : airports.filter { $0.localizedCaseInsensitiveContains(text) }
}
.receive(on: DispatchQueue.main) // UI state back on main
.assign(to: &$suggestions)
}
}go deeper
Recall that debounce waits for a pause, removeDuplicates skips repeats and receive(on: DispatchQueue.main) is how a Combine pipeline gets back to the main queue for UI.
Explain that debounce restarts its timer per value and re-emits on its scheduler, why removeDuplicates belongs after it, and that a stage runs on whatever thread delivered to it.
Show deliberate scheduler placement: background work behind one receive(on:), a single hop back to main before UI state, and an injected scheduler so the pipeline's timing is testable.
Set the codebase's scheduler conventions, which main scheduler UI code uses and how schedulers are injected, so every search and form pipeline is written and tested the same way.
## The pipeline at a glance A search-as-you-type field in Combine usually starts from an **`@Published` property** on a view model, `@Published var query = ""`, whose projected `$query` publisher emits the current text and then every change. Three operators turn that keystroke stream into a sensible stream of queries: 1. **`debounce(for:scheduler:options:)`** waits until the text has stopped changing for an interval. 2. **`removeDuplicates()`** skips a settled query equal to the one before it. 3. **`receive(on:options:)`** delivers the rest of the pipeline on a chosen scheduler, typically the main queue for UI state. Each stage changes either *which* values pass or *where* they are delivered, and mixing those two concerns up is the most common source of bugs here. ## debounce: wait for the pause `debounce` holds the latest value and starts a timer on the scheduler you pass. Each new value replaces the held one and **restarts the timer**; only when a full interval passes without a new value is the held value published. Apple's documentation walks through a timeline in which values that arrive faster than the interval are discarded and only the value before a pause gets through. For a field typed as `l`, `lo`, `lon` within 300 ms, the downstream sees only `lon`, 300 ms after the last keystroke. Two details matter in review: - The **scheduler argument is where the timer runs and where the value is re-emitted**. `debounce(for: .milliseconds(300), scheduler: DispatchQueue.main)` delivers on the main queue even if the upstream sent from elsewhere. - The interval is a `SchedulerTimeType.Stride` of that scheduler, written with conveniences such as `.milliseconds(300)` or `.seconds(0.5)`. ## removeDuplicates: settled queries only `removeDuplicates()` is available when `Output` is `Equatable` and compares each value with the **previous value it let through**; `removeDuplicates(by:)` takes your own predicate, for example to compare trimmed, lowercased text. Order matters: - **After `debounce`**, it compares settled queries. Type `lon`, pause, type `d`, backspace, pause: `debounce` emits `lon` twice and `removeDuplicates()` drops the second. - **Before `debounce`**, it compares raw keystrokes, which rarely repeat back to back, so the same settled query can still go through twice. ## Where each stage runs Combine does not move work between threads on its own. A sink or operator runs on whatever thread delivered the value to it, unless an operator with a scheduler changes that. | Stage | Delivers on | |---|---| | `$query` | The thread that assigned `query` (the main thread for a text field) | | `debounce(for:scheduler:)` | The scheduler you pass it | | `removeDuplicates()`, `map`, `filter` | Whatever thread delivered to them | | `receive(on: work)` | The `work` queue, for everything after it | | `receive(on: DispatchQueue.main)` | The main queue, for everything after it | | `subscribe(on:)` | Moves subscription, demand requests and `cancel()` upstream; not value delivery | Apple's documentation recommends `receive(on:)` over calling `DispatchQueue.main.async` inside a sink, and notes that `receive(on:)` does not change the scheduler used for the subscriber's `receive(subscription:)` call. ## debounce versus throttle `throttle(for:scheduler:latest:)` publishes either the first or the most recent value received in each interval, so it **keeps emitting while the user types**. That suits a continuous signal you want to sample, such as scroll position, not a query you want to send once the user stops. For search, `debounce` is the operator that matches the intent. ## Testing the timing A pipeline that hard-codes `DispatchQueue.main` can only be tested by waiting for real time to pass, which makes tests slow and flaky. The usual fix is to make the scheduler a dependency of the view model: - Declare the initializer generic over `S: Scheduler` and pass the scheduler to `debounce` and `receive(on:)`. - Default it to `DispatchQueue.main` in the app. - In tests, pass a scheduler whose clock the test advances by hand, such as a test scheduler from a testing library, then assert which queries came out and when. The operators stay identical; only the clock changes. ## Common mistakes - Expecting `subscribe(on: DispatchQueue.main)` to put the sink on the main queue. It only affects upstream work. - Adding `receive(on: DispatchQueue.main)` straight after a main-queue `debounce` with nothing in between. It is redundant: `debounce` already delivers on that queue. - Matching or filtering a large list on the main queue because nobody added a `receive(on:)` to a background queue first. - Using `RunLoop.main` and `DispatchQueue.main` interchangeably without a reason: pick one scheduler for UI in the codebase and use it consistently. - Forgetting the initial value: `$query` sends the current, empty text on subscription, so an empty query reaches the pipeline after the first interval unless you handle it, for example by mapping short text to no suggestions.
- Why not call DispatchQueue.main.async inside the sink instead of using receive(on:)?Apple's documentation recommends `receive(on:)` over explicit dispatch inside subscribers. The hop then lives in the pipeline where a reviewer can see it, it applies to the completion event too, and the scheduler can be injected so a test can control time and threading instead of waiting on the real main queue.
- What does subscribe(on:) change, and where would it actually help?`subscribe(on:)` moves upstream work, the subscription itself, demand requests and `cancel()`, onto its scheduler; it does not decide where values are delivered. It helps when subscribing triggers expensive work, such as a `Deferred` publisher that reads a file when subscribed. On an `@Published` text field it moves nothing useful.
- How would you test this pipeline without waiting 300 ms per case?Make the scheduler a dependency, for example a generic `S: Scheduler` parameter that defaults to `DispatchQueue.main`, and in tests pass a scheduler whose clock the test advances by hand, such as a test scheduler from a testing library. The debounce interval, the duplicate filtering and the ordering of results can then be asserted instantly.
- debounce sends the first keystroke, then ignores the rest for the interval
- Combine delivers values on the main thread by default
- subscribe(on: DispatchQueue.main) makes the sink run on the main queue
- removeDuplicates works the same before debounce as after it
- throttle and debounce are interchangeable for search-as-you-type