With Combine, why does a sink on a view model's @Published property stop delivering values when you don't keep the AnyCancellable it returns?
answer
- what sink hands back to you
- a token with a lifetime
- deinit calls cancel()
- store(in:) into a Set<AnyCancellable>
- the unused-result warning on sink
basics
~20 sCombine's sink returns an AnyCancellable, and an AnyCancellable calls cancel() when it is deinitialized. If nothing keeps it, the subscription ends at once and later values never arrive; keep it in a property or with store(in:).
solid answer
~40 s`sink(receiveValue:)` creates a `Subscribers.Sink`, requests an unlimited number of values and returns an `AnyCancellable` for the subscription. An `AnyCancellable` calls `cancel()` when it is deinitialized, so a result you discard with `_ =`, or keep in a local that goes out of scope, ends the subscription straight away. With an `@Published` property's `$` publisher this is easy to miss: the publisher sends its current value while the subscription is being set up, so the sink fires once and then goes silent. Keep the token for as long as you want values, usually with `.store(in: &cancellables)` into a `Set<AnyCancellable>` the view model owns; the subscriptions then end when the view model is released. To stop one earlier, call `cancel()` on it or drop the reference you kept.
code
swift · 18 linesimport Combine
final class AirportFieldModel {
@Published var query = ""
private var cancellables = Set<AnyCancellable>()
func startBroken() {
// The AnyCancellable is discarded at once: the sink sees the
// current value, then the subscription is cancelled.
_ = $query.sink { print("broken sink:", $0) }
}
func start() {
$query
.sink { print("kept sink:", $0) }
.store(in: &cancellables)
}
}go deeper
Recall that sink returns an AnyCancellable and that releasing it cancels the subscription. Show store(in:) into a Set the view model owns.
Explain the mechanics: sink creates a Subscribers.Sink with unlimited demand, the token's deinit calls cancel(), and an @Published publisher's initial value makes a dropped token look as if it worked once.
Tie each subscription's lifetime to its owner on purpose: one Set per owner, a separate optional token for a pipeline you restart, and no strong self capture in sinks that owner stores.
Agree a team convention for where tokens live and how pipelines end, so code review catches dropped tokens and owner-retaining sinks consistently rather than by luck.
## What sink actually returns In Combine, a **publisher** emits values over time and a **subscriber** receives them. `sink(receiveValue:)` and `sink(receiveCompletion:receiveValue:)` are convenience operators: they build a `Subscribers.Sink`, attach it to the publisher, and, as Apple's documentation puts it, immediately request an unlimited number of values before returning. What you get back is not the values and not the subscriber itself but an **`AnyCancellable`**, a type-erased token whose only jobs are to cancel the subscription and to be stored. The key line in the `AnyCancellable` documentation is short: an `AnyCancellable` instance **automatically calls `cancel()` when deinitialized**. The `sink` documentation says the same from the other side: the return value should be held, otherwise the stream will be cancelled. The subscription lives exactly as long as that token does. There are two `sink` variants. `sink(receiveValue:)` is available only when the publisher's `Failure` is `Never`, which is the case for an `@Published` property; a publisher that can fail needs `sink(receiveCompletion:receiveValue:)`, whose first closure receives `.finished` or `.failure`. Both return an `AnyCancellable`, and both behave the same way when that token is dropped. `assign(to:on:)` is the other built-in subscriber, and it also hands back a token you must keep. The rule is the same for any subscriber you build yourself: something has to own the cancellation token, or the subscription has no reason to exist past the current statement. ## Why a dropped token ends the subscription Here is the sequence when the token is not kept: 1. `$query.sink { ... }` subscribes to the `@Published` property's publisher. 2. During subscription the publisher delivers its **current value**, so the closure runs once with whatever `query` holds now. 3. `sink` returns the `AnyCancellable`. Nothing references it, so it is released at the end of the statement (with `_ =`) or at the end of the scope (with a local `let`). 4. Its `deinit` calls `cancel()`, the subscription is torn down, and every later assignment to `query` goes nowhere. Step 2 is what makes this bug confusing in a view model: the first value arrives, so the pipeline looks wired up, and only later changes go missing. The compiler does warn you for a bare call, with `result of call to 'sink(receiveValue:)' is unused`, but `_ =` silences that warning without fixing anything. ## Keeping the subscription alive The fix is to give the token an owner whose lifetime matches the work: - **A `Set<AnyCancellable>` on the view model** is the usual home. `store(in:)` appends the token, and when the view model is deallocated the set is released, each token deinitializes, and each subscription is cancelled. - **A dedicated optional property** such as `var suggestionsCancellable: AnyCancellable?` suits a pipeline you restart. Assigning a new token releases the old one, which cancels the old subscription. - **An array** works too: `store(in:)` also accepts any range-replaceable collection of `AnyCancellable`. - **`assign(to:)` on an `@Published` property** returns no token at all; its subscription ends with the property's storage. ## Ways a subscription ends | What happens | Effect on the subscription | |---|---| | The token is released | `deinit` calls `cancel()`; no more values or completion | | You call `cancel()` on the token | Cancelled immediately, token can still be held | | The publisher sends `.finished` or a failure | The subscription is over; no more values will come | | The owner of the `Set` is deallocated | Every token in it is released and cancelled | A publisher that finishes on its own, such as `Just` or a request publisher, ends the subscription regardless of the token. The token matters most for publishers that do not finish: an `@Published` property, a subject you keep open, a timer. ## Mistakes that look like a Combine bug - **Subscribing in a method and keeping the token in a local `let`.** It deinitializes when the method returns. - **Silencing the warning with `_ =`.** The warning was the hint that the token mattered. - **Calling `.cancel()` in a chain "to be tidy".** It cancels on the spot. - **Assuming cancellation needs manual cleanup.** Releasing the token is enough; you do not have to call `cancel()` before letting it go. - **Storing tokens in the owner while the sink captures that owner strongly.** That is the opposite failure: the subscription never ends because the owner can never be released. Capture `[weak self]` in such a sink. The snippet below shows the broken and the fixed form side by side; run against an `@Published` property it prints the current value from both sinks, then only the kept sink sees the next assignment.
- If a view model keeps its tokens in a Set<AnyCancellable>, when do those subscriptions end?When the set is released, normally when the view model deallocates: each `AnyCancellable` is deinitialized and calls `cancel()`. That only works if the subscriptions do not keep the view model alive. A sink that captures `self` strongly, stored in `self`'s own set, forms a cycle, so neither ever goes away; capture `[weak self]` or republish with `assign(to:)`.
- How do you stop one subscription early without touching the others in the same Set?Keep that subscription out of the shared set, in its own `AnyCancellable?` property. Call `cancel()` or set the property to `nil` to end it; assigning a new token releases the previous one, which cancels it. That is the usual way to restart a single pipeline, for example when a screen switches to a different data source.
- Does a sink on a publisher that has already finished still need its token?Once a publisher sends `.finished` or a failure, no more values arrive, so keeping the token changes nothing. The token matters for publishers that never finish on their own, such as `@Published` properties, subjects kept open and timers, and those are exactly where a dropped token silently stops the updates.
- A sink keeps itself alive until its publisher completes
- Writing _ = in front of sink is a harmless way to silence the warning
- Keeping the token in a local let inside the method is enough
- An AnyCancellable must be cancelled by hand or the subscription leaks
- The sink went quiet because @Published emits only once per subscriber