skip to content

With Combine, what does a new subscriber get from a PassthroughSubject, a CurrentValueSubject and an @Published property's $ publisher, and when?

level: middleimportance: should knowfreq 62%

answer

  1. which of them remembers a value
  2. sends with nobody listening
  3. CurrentValueSubject's value property
  4. @Published publishes in willSet
  5. combineLatest waits for every input

basics

~20 s

A PassthroughSubject has no current value: a subscriber sees only later sends, and sends with no subscriber are dropped. A CurrentValueSubject and an @Published $ publisher send their current value on subscription, then each change; @Published sends in willSet, before the property changes.

solid answer

~50 s

`PassthroughSubject` suits events such as a Search tap: it has no initial value and no buffer, so a subscriber sees only what is sent after it subscribes, and a send with no subscriber, or no demand, is dropped. `CurrentValueSubject` holds state: you create it with a value, a new subscriber gets `value` at once, and `send(_:)` and setting `value` are equivalent. An `@Published` property's `$` publisher also starts with the current value, but its `Failure` is `Never`, it never finishes on its own, and it publishes in the property's `willSet`, so a sink that reads the property back sees the old value. This matters with `combineLatest`, which emits only once every input has emitted: two `@Published` fields enable the Search button immediately, while a `PassthroughSubject` input leaves it waiting for a first send. After `send(completion:)`, a subject ignores further sends.

code

swift · 18 lines
swift
import Combine

final class TripFormModel {
    @Published var passengers = 1
    @Published var dates: ClosedRange<Int>? = nil   // day numbers, for brevity
    let searchTapped = PassthroughSubject<Void, Never>()
    let isSearchEnabled = CurrentValueSubject<Bool, Never>(false)
    private var cancellables = Set<AnyCancellable>()

    init() {
        $passengers
            .combineLatest($dates)
            .map { count, range in (1...9).contains(count) && range != nil }
            .removeDuplicates()
            .sink { [isSearchEnabled] in isSearchEnabled.send($0) }
            .store(in: &cancellables)
    }
}

go deeper

for a junior

Recall that PassthroughSubject has no current value, CurrentValueSubject and @Published start with one, and that @Published lives on class properties.

for a middle

Explain what a late subscriber gets from each, that @Published publishes in willSet, and why combineLatest stays silent until every input has emitted.

for a senior

Choose by meaning: events as passthrough, state as current value or @Published, subjects kept private behind AnyPublisher, and no accidental completion of a shared subject.

for a principal

Decide where state lives in the app's Combine layer, which types expose publishers and which may send, so screens subscribe late without missing state.

## Three ways to feed a pipeline Combine gives an app three common entry points for its own values. A **subject** is a publisher you push values into with `send(_:)`; an **`@Published` property** publishes every assignment through its projected `$` publisher. What separates them is memory: whether a subscriber that arrives late gets anything. | Entry point | Initial value | A new subscriber first receives | Can fail or finish | Typical use | |---|---|---|---|---| | `PassthroughSubject<Output, Failure>` | None | Only values sent after it subscribes | Yes, via `send(completion:)` | Events: a tap, a refresh request | | `CurrentValueSubject<Output, Failure>` | Required in `init(_:)` | The current `value`, at once | Yes, via `send(completion:)` | State outside a class property | | `@Published var` with `$name` | The property's value | The current value, at once | No: `Failure` is `Never`, and it never finishes on its own | View-model state | ## PassthroughSubject: events Apple's documentation says a `PassthroughSubject` has no initial value and no buffer of the most recent element, and that it **drops values if there are no subscribers or its current demand is zero**. That is the right behaviour for an event: a Search tap that happened before anyone listened should not fire later. It is the wrong behaviour for state: a subscriber that arrives after the last change has nothing to show until the next one. ## CurrentValueSubject: state with a value A `CurrentValueSubject` keeps the most recent element. A new subscriber receives it immediately, then every later one. Calling `send(_:)` also updates `value`, and setting `value` directly sends it, so the two are equivalent. You can read `value` synchronously at any time, which makes it handy for state held outside a class, for example in a service that several screens subscribe to. ## @Published: a property that publishes `@Published` is class-constrained: it is available only on properties of classes. Its `$` publisher sends the current value when you subscribe and then a value on every assignment. Three details catch people: - **Timing.** Apple's documentation states that publishing happens in the property's **`willSet`**, so subscribers get the new value before it is stored. A sink that reads `self.passengers` instead of its closure parameter sees the **old** value. - **No filtering.** It publishes on every assignment, even when the new value equals the old one; add `removeDuplicates()` when that matters. - **No completion.** The `Failure` type is `Never` and the publisher never finishes on its own, so subscriptions to it last until they are cancelled. ## How this shows up in form validation `combineLatest` emits a tuple of the latest values **only after every input has emitted at least once**, and then again whenever any input changes. On a flight-search form: 1. `$passengers.combineLatest($dates)` emits immediately, because both `@Published` publishers send their current values on subscription, so the Search button gets its initial `false` straight away. 2. If `dates` were a `PassthroughSubject`, the combined publisher would stay silent until the first date range was sent, and the button would keep whatever state it was created with. 3. Mapping the tuple to a `Bool` and adding `removeDuplicates()` stops the button from being reset on every change that leaves validity as it was. ## Choosing between them A quick way to decide in review: 1. Is it something that **happened**, a tap, a pull to refresh, a message? Use a `PassthroughSubject`; late subscribers should not see old events. 2. Is it something that **is**, the current passenger count, the selected dates? Use an `@Published` property on the view model, or a `CurrentValueSubject` when the state lives outside a class property or must be able to finish. 3. Does any caller other than the owner need to send? Usually not; expose only a publisher. Getting this wrong produces the classic symptoms: a screen that shows nothing until the user acts, or an action replayed when a screen appears. ## Pitfalls - Exposing a subject publicly. Keep it private and expose `eraseToAnyPublisher()` so callers can subscribe but not send or complete it. - Completing a subject by accident. Once a subject receives `send(completion:)`, later `send(_:)` calls are ignored and a new subscriber receives only the completion. - Using a `PassthroughSubject` for state and wondering why a late screen shows nothing. - Reading the property inside its own sink and acting on the stale value.

  • Why does a sink on $passengers that reads self.passengers log the previous count?
    `@Published` publishes in the property's `willSet`, so subscribers receive the new value before it is stored; reading the property inside the closure returns the old one. Use the value passed to the closure. If the work really needs the stored state, derive it from the published value rather than reading back the property.
  • How should a view model expose a subject to the views that subscribe to it?
    Keep the subject `private` and expose `subject.eraseToAnyPublisher()` as an `AnyPublisher`. Subscribers can then receive values but cannot call `send(_:)` or `send(completion:)`, so the view model stays the only writer and no caller can finish the stream for everyone.
  • What does a subscriber get from a CurrentValueSubject that has already finished?
    Only the finished completion, with no value. Once a subject has sent a completion it ignores later `send(_:)` calls, and new subscribers immediately receive that completion. A shared service that finishes a subject by mistake therefore silently stops every screen that subscribes afterwards.

  • PassthroughSubject replays its last value to new subscribers
  • @Published publishes after the property is set, so reading it in sink is safe
  • Setting a CurrentValueSubject's value does not notify subscribers; only send does
  • combineLatest emits as soon as any one of its inputs emits
  • @Published works on properties of structs as well as classes