Subscription Mechanism in Combine
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.
- The
subscriber
, subscribes to thepublisher
. - The
publisher
creates thesubscription
then sends to the Subscriber (callingreceive(subscription:)
). - The
subscriber
requests values from thesubscription
by sending it the number of values it wants (calling the subscription’srequest(_:)
method). - The
subscription
begins the work and starts emitting values. It sends them one by one to the subscriber (calling the subscriber’sreceive(_:)
method). - Upon receiving a value, the
subscriber
returns a newSubscribers.Demand
, which adds to the previous demand. - 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.