Demystifying PublishSubject, PublishRelay, BehaviorSubject, and BehaviorRelay in RxSwift

Harshit Parakh

--

Introduction:

RxSwift, the reactive programming framework for Swift, offers a variety of subjects and relays that serve as important building blocks for implementing reactive behavior. Among them, PublishSubject, PublishRelay, BehaviorSubject, and BehaviorRelay are widely used and play distinct roles in handling event streams. In this article, we’ll dive into the differences between these four components and provide practical examples to illustrate their usage.

PublishSubject:

PublishSubject is a subject that allows multiple subscribers to receive subsequent events. It does not cache past events and only delivers events to subscribers that have subscribed after the event occurred. Let’s consider an example:

Output

As we can see, the first subscriber only receives events that occur after its subscription, while the second subscriber receives both the latest event and subsequent events.

PublishRelay:

PublishRelay is similar to PublishSubject but lacks the ability to send errors or completed events. It provides a more simplified API for cases where you don’t need to handle error or completion events explicitly. Here’s an example:

Output

As shown, PublishRelay is straightforward to use and ideal for scenarios where you don’t require error handling or completion events.

BehaviorSubject:

BehaviorSubject is a subject that caches the most recent event and delivers it immediately to new subscribers. It ensures that every subscriber receives the most recent event upon subscription. Consider the following example:

Output

As seen, the initial subscriber receives the initial event as well as subsequent events, while the second subscriber receives the most recent event upon subscription.

BehaviorRelay:

BehaviorRelay is similar to BehaviorSubject but provides a more convenient API for updating its value. It is mutable and encapsulates a BehaviorSubject within itself. Here’s an example:

Output

As demonstrated, the BehaviorRelay behaves similarly to BehaviorSubject, ensuring new subscribers receive the most recent event and allowing for easy value updates.

Conclusion:

In this article, we explored the differences between PublishSubject, PublishRelay, BehaviorSubject, and BehaviorRelay in RxSwift. PublishSubject allows multiple subscribers but doesn’t cache events, while PublishRelay simplifies event handling without error or completion events. BehaviorSubject caches and delivers the most recent event to new subscribers, and BehaviorRelay offers a mutable variant with a more convenient API for updating values. Understanding these components is crucial for building robust and reactive applications with RxSwift.

Sign up to discover human stories that deepen your understanding of the world.

--

--

No responses yet

Write a response