Subjects in Combine

DevTechie
DevTechie
Published in
6 min readApr 30, 2023

--

Subjects in Combine

One of the key components of Combine is the concept of a subject. Let’s take a closer look at subjects in Combine framework and how it can be used to handle data streams.

A subject is a type that can both act as a publisher (i.e., a source of values) and a subscriber (i.e., a receiver of values) at the same time.

Subjects are used to bridge the gap between imperative and reactive programming paradigms. They allow us to create a single entity that can both receive and send values to multiple subscribers, just like a traditional observable sequence in reactive programming.

There are two types of subjects in Combine PassthroughSubject & CurrentValueSubject.

PassthroughSubject

A PassthroughSubject is the most basic type of subject in Combine. It simply passes through the values it receives to its subscribers. When a new subscriber is added to a PassthroughSubject, it will start receiving all values sent by the subject from that point onwards. A PassthroughSubject does not buffer any values, so any subscribers added after a value has been sent will not receive that value. When a subscriber is connected and requests data, it will not receive any values until a .send() call is invoked.PassthroughSubject doesn’t maintain any state, it only passes through provided values. Calls to .send() will then send…

--

--