With Combine, why does a view model that calls assign(to:on: self) or captures self in sink, storing the token in its own Set, never deinit?
answer
- follow who holds whom
- Subscribers.Assign keeps its object strongly
- self owns the Set of tokens
- @Published never completes to break it
- assign(to: &$property), from iOS 14
basics
~20 sSelf owns the AnyCancellable, which keeps the subscriber, which holds self strongly: assign(to:on:) keeps its object and a sink keeps what its closure captures. An @Published upstream never completes, so the loop stays; use assign(to: &$property) (iOS 14) or [weak self].
solid answer
~40 sIt is an ownership loop: the view model's `Set<AnyCancellable>` keeps each subscription, the subscription keeps its subscriber, and the subscriber keeps the view model. `Subscribers.Assign`, which `assign(to:on:)` creates, holds its `object` strongly, and Apple's documentation says it lets go only when the upstream completes; a `sink` closure that uses `self` without `[weak self]` holds it the same way. An `@Published` property, a subject left open or a timer never completes on its own, so `deinit` never runs, the tokens are never released and the pipelines keep working for a screen that is gone. Break the edge back to `self`: since iOS 14, `assign(to: &$summary)` republishes into an `@Published` property with no token at all and ends with that property's storage; for a sink, capture `[weak self]`, or capture only the objects the closure needs.
code
swift · 27 linesimport Combine
final class PassengerStepperModel {
@Published var passengers = 1
@Published var summary = ""
private var cancellables = Set<AnyCancellable>()
init() {
// Leaks: Subscribers.Assign holds self strongly, and self holds it.
// $passengers.map { "\($0) passengers" }
// .assign(to: \.summary, on: self)
// .store(in: &cancellables)
// iOS 14+: no AnyCancellable, ends when `summary`'s storage goes away.
$passengers
.map { "\($0) passengers" }
.assign(to: &$summary)
// A sink that touches self captures it weakly.
$passengers
.sink { [weak self] count in self?.logChange(count) }
.store(in: &cancellables)
}
private func logChange(_ count: Int) { print("passengers now", count) }
deinit { print("PassengerStepperModel deinit") }
}go deeper
Recall that assign(to:on:) and a sink capturing self can keep a view model alive, and that [weak self] or assign(to: &$property) avoids it.
Explain the three references in the loop, that Subscribers.Assign holds its object strongly until completion, and why @Published upstreams never complete.
Diagnose from a missing deinit or a memory graph, choose the fix per subscriber type, and prove it with a weak-reference unit test rather than by eye.
Make the safe forms the house style, assign(to:) for @Published targets and capture lists in sinks, and have reviews flag assign(to:on: self) on sight.
## The ownership loop A Combine subscription is an object graph. When a view model subscribes and keeps the token itself, three strong references form a circle: 1. The view model owns a `Set<AnyCancellable>` and the token stored in it. 2. The token keeps the subscription, and the subscription keeps its **subscriber**. 3. The subscriber keeps the view model: `Subscribers.Assign` through its `object`, a `Subscribers.Sink` through whatever its closure captured. Nothing outside the circle needs to hold the view model for it to stay alive. When the screen is dismissed, the view model's `deinit` never runs, so the set is never released, so no token calls `cancel()`. The pipelines keep running for a screen nobody can see, and every value they receive does work for nothing. Strong reference cycles in closures in general are a Swift memory topic; what is specific to Combine is which subscriber holds what, and when it lets go. ## assign(to:on:) and its strong object `assign(to:on:)` sets a key path on an object for every value. Apple's documentation for it carries an explicit warning: the `Subscribers.Assign` instance **maintains a strong reference to `object`**, and sets it to `nil` when the upstream publisher **completes**, normally or with an error. So the cycle depends on the upstream: - An upstream that finishes, such as `Just` or a one-shot request, releases the object when it completes. - An `@Published` property's publisher, a subject that is never completed, or a timer **never completes on its own**, so the strong reference is permanent. `$passengers.map { ... }.assign(to: \.summary, on: self).store(in: &cancellables)` is the textbook case: an `@Published` upstream, the object is `self`, and the token lives in `self`. ## sink closures that capture self `sink(receiveValue:)` stores its closure in the subscriber. If the closure calls a method on `self` or reads a property without a capture list, it captures `self` strongly, and storing the token in `self` closes the loop. `[weak self]` turns the back edge into a weak reference: the closure checks `self` and does nothing once the view model is gone. When the closure needs only a collaborator, capturing that object directly in the capture list, as in `[formatter]`, avoids capturing `self` at all. ## assign(to:) since iOS 14 iOS 14 added `assign(to:)` for a publisher whose `Failure` is `Never`, taking an `inout` reference to an `@Published` property's publisher: `upstream.assign(to: &$summary)`. Apple's documentation says it manages the subscription's life cycle itself, cancelling it when the `Published` instance deinitializes, which is why it **returns no `AnyCancellable`**. The same documentation names the `assign(to:on: self)` version as the one that could cause a reference cycle. Every app that deploys back to iOS 17 can use `assign(to:)` without an availability check. ## View controllers have the same problem Nothing here is specific to view models. A UIKit view controller that subscribes in `viewDidLoad()`, stores the token in its own `Set<AnyCancellable>`, and calls `self.tableView.reloadData()` inside a strong sink is kept alive after it is popped. Its view hierarchy stays in memory with it, and every new value still reloads a table no one can see. The same is true of a coordinator or a service that owns its subscriptions. Wherever an object both owns the token and is referenced by the subscriber, the object can never be released, so the check in review is always the same: who owns the token, and what does the subscriber hold? ## Choosing the fix | Situation | Fix | |---|---| | Republishing into one of the object's own `@Published` properties | `assign(to: &$property)` | | Assigning onto a property that is not `@Published` | `sink { [weak self] in self?.value = $0 }` | | A sink that calls the object's methods | `[weak self]` with `guard let self` or optional chaining | | A sink that needs only a collaborator | Capture that object, not `self` | | `assign(to:on:)` on an upstream that completes | Released on completion, per Apple's documentation; prefer `assign(to:)` or a weak capture anyway | ## How to confirm a fix - Log in `deinit` and dismiss the screen; a missing log line is the first signal. - In a unit test, create the view model, keep a `weak var` to it, drop the strong reference, and assert the weak one is `nil`. - In the memory graph debugger, follow the references into the view model back to the subscriber or closure that holds it. The snippet keeps the leaking form as a comment and shows both fixes; run as a script it prints the summary and then the `deinit` line when the last reference is dropped.
- Why doesn't assign(to: &$summary) create the same cycle?It returns no `AnyCancellable`, so there is no token for `self` to store, and Apple's documentation says the operator cancels the subscription itself when the `Published` instance deinitializes. Nothing in the pipeline has to outlive the object, so releasing the view model releases the property storage and ends the subscription with it.
- Would [unowned self] be a better fix than [weak self] in a sink?Only if you can prove the closure never runs after `self` is freed. `unowned` crashes in that case, while `weak` turns it into a no-op at the cost of an optional check. Because a pipeline's delivery timing depends on schedulers and upstreams you may change later, `[weak self]` is the safer default in Combine closures.
- Does assign(to:on: self) leak when the upstream finishes?Not permanently: Apple's documentation says `Subscribers.Assign` sets its object to `nil` when the upstream completes, normally or with an error. The permanent leak needs an upstream that never completes, which is exactly what `@Published` properties, open subjects and timers are, and those are the usual upstreams in a view model.
It is like a gym membership that renews automatically from your account until you cancel it, where the only way to cancel is to close the account, and the account cannot be closed while a membership is active.
- assign(to:on:) holds its object weakly, so assigning onto self is safe
- Tokens in the view model's Set are cancelled when its screen is dismissed
- assign(to: &$property) returns an AnyCancellable that you must store
- Every Combine closure needs [weak self], even one that never mentions self
- The cycle breaks by itself the next time the upstream sends a value
Assumes the iOS 27.1 SDK with an iOS 17 deployment target; assign(to:) into an @Published property is iOS 14 and later, so it needs no availability check.