Subscription Mechanism in Combine

Ario Liyan
2 min readApr 30, 2024

--

In this short post we read about subscription process from start to the end in Combine framework. This post is one in a series of Posts on Combine in Swift.

Publishers by nature are inert entities. When the subscriber subscribes to a publisher the publisher instantiates the subscription and start works.

  1. The subscriber, subscribes to the publisher.
  2. The publisher creates the subscription then sends to the Subscriber (calling receive(subscription:)).
  3. The subscriber requests values from the subscription by sending it the number of values it wants (calling the subscription’s request(_:) method).
  4. The subscription begins the work and starts emitting values. It sends them one by one to the subscriber (calling the subscriber’s receive(_:) method).
  5. Upon receiving a value, the subscriber returns a new Subscribers.Demand, which adds to the previous demand.
  6. The subscription keeps sending values until the number of values sent reaches the total requested number.

Note that if a subscription sends total values requested from the subscriber it should awaits for the signal before sending more values. This mechanism is inherent in the heart of the Combine framework. This can be bypassed but may result in unpredictable situations.

If there is an error or the subscription’s values source completes, the subscription calls the subscriber’s receive(completion:) method.

Next

--

--

Ario Liyan

As an iOS developer with a passion for programming concepts. I love sharing my latest discoveries with others and sparking conversations about technology.