Combine — Role of Cancellable Explained

DevTechie
DevTechie
Published in
6 min readJul 8, 2023

--

Combine — Role of Cancellable Explained

A cancellable in the Combine framework is an object that enables the manual or automatic cancellation of a publisher. When a cancellable is created, it is returned to the caller and then can be used to cancel the publisher.

Cancellable gives publisher a way to terminate the service when emitted events are no longer needed or in case of an error scenario. This is essential because, if the publishers doesn’t stop it may broadcast values endlessly, which can lead to memory leaks or other unexpected issues.

In other words, cancellable gives us ability to turn off the event stream at some point in time where events are no longer needed.

Cancellable can be created using the sink subscriber, which returns a AnyCancellable object. This object can be stored and used to cancel the publisher later, either manually or automatically.

The sink method creates the subscriber and immediately requests an unlimited number of values before returning the subscriber. Returned cancellable instance can be used to end the assignment of the received value which results in the deallocation of the result to tear down the subscription stream.

Some of the top reasons as why its important to call cancel() on a sink subscriber.

  • To prevent memory leaks: If we don’t cancel a sink

--

--