AnyCancellable and subscription lifetime

Combine Mid-level Swift 5.1+ iOS 13+ Reviewed By Alok Singh

Spot the bug

The clock never updates. Tap the line that causes it.

  1. final class ClockModel {
  2. var now = Date()
  3. func start() {
  4. _ = Timer.publish(every: 1, on: .main, in: .common)
  5. .autoconnect()
  6. .sink { [weak self] date in self?.now = date }
  7. }
  8. }
Hint 1 of 1

What happens when an AnyCancellable is deallocated?

Choose an answer, then open Show answer below to check it.

Show answer
  • Answer: line 4 _ = Timer.publish(every: 1, on: .main, in: .common)

Line 4 discards the AnyCancellable, so the subscription is cancelled at once. Store it: .store(in: &cancellables) with private var cancellables = Set<AnyCancellable>().

30-second answer

Subscribing returns an AnyCancellable, which cancels the subscription when it is deallocated. Keep it alive for as long as you want values, usually in a Set<AnyCancellable> owned by the object, with .store(in: &cancellables). When the owner is freed, its subscriptions are cancelled too, as long as the sink closures don't strongly capture the owner.

Practise saying it · 30 s. No recording, just a timer

Explain AnyCancellable.

Say your answer out loud, then check which of these points you covered:

  • Cancels on deinit
  • Store in a set
  • Avoid strong self

Deep dive

Discarding the cancellable (_ =) cancels immediately.

Capture [weak self] in sinks stored on self to avoid cycles.

Call cancel() or remove from the set to stop early.

One cancellable property works for a single replaceable subscription.

Common mistakes

  • Not storing the cancellable.
  • Strong self in sink closures stored on self.

Senior take & follow-ups

Seniors tie subscription lifetime to the owner and avoid cycles.

Follow-up questions

Think of your answer first, then open the hint.

  1. Why does the timer stop immediately?

    Show hint

    The cancellable was dropped.

  2. How do you replace a subscription?

    Show hint

    Assign a new cancellable to a single property.

Suggest a fix if something here is wrong or out of date.