PublishSubject
is a type of observable in RxSwift that begins empty and only emits new events to its subscribers. It does not store any previous events; subscribers will only receive events that are emitted after they subscribe. This makes PublishSubject
ideal for handling and broadcasting new events in real-time, without retaining any historical data.
Key Characteristics:
- No Initial Value:
PublishSubject
doesn’t hold an initial value, unlikeBehaviorSubject
. - Emits Only New Events: Subscribers only receive events emitted after they subscribe.
- Broadcasts Events: It sends events to all its subscribers simultaneously, making it suitable for situations where multiple parts of an app need to react to the same event in real-time.
Common Use Cases:
- Event Streams: For events like button taps, notifications, or any actions that need to be observed without retaining past events.
- UI Updates: To trigger UI changes across multiple views or view controllers.
- Delegation Pattern Replacement: For creating reactive callbacks, replacing traditional delegation with observable event handling.
Example Usage
import RxSwift
let disposeBag = DisposeBag()
let subject = PublishSubject<String>()
// Subscriber 1
subject.subscribe(onNext: {
print("Subscriber 1 received: \($0)")
}).disposed(by: disposeBag)
// Emit events
subject.onNext("Hello")
subject.onNext("RxSwift")
// Subscriber 2 subscribes later
subject.subscribe(onNext: {
print("Subscriber 2 received: \($0)")
}).disposed(by: disposeBag)
// Emit more events
subject.onNext("New Event")
Output:
Subscriber 1 received: Hello
Subscriber 1 received: RxSwift
Subscriber 1 received: New Event
Subscriber 2 received: New Event
Explanation:
- Subscriber 1 receives all events from
"Hello"
onward. - Subscriber 2 only receives events starting from
"New Event"
, as it subscribed after the previous events were emitted.
In this way, PublishSubject
provides a flexible way to handle real-time event streams, ensuring that only current and future events are propagated to subscribers.
Leave a Reply