Member-only story
Combine Framework (Subject, CombineLatest, Zip)
13 min readSep 25, 2024
Subject Publisher
It’s a special kind of publisher that allows you to emit values manually. It acts as both a publisher and a subscriber. This is useful when you want to bridge imperative code (like button taps) cal
Use Cases of Subject
:
- To convert imperative code (like delegates, closures, or events) into reactive streams.
- Manually send values that might come from user input or external triggers.
There are two main types of subjects:
1. PassthroughSubject:
- It doesn’t store the values, meaning subscribers won’t get any previously emitted values when they subscribe. If a subscriber subscribes after values have already been emitted, they will not receive the past values.
Example with PassthroughSubject
Here’s an example to understand the workings of PassthroughSubject
:
// Create a PassthroughSubject that will publish integers and never fail.
let subject = PassthroughSubject<Int, Never>()
// Subscriber #1
let subscription1 = subject.sink { value in
print("Subscriber #1 received value: \(value)")
}
// Send values through the subject
subject.send(10)
subject.send(20)
// Subscriber #2 subscribes after some values have already been sent
let subscription2 = subject.sink { value in
print("Subscriber #2 received value: \(value)")
}
// Send another value
subject.send(30)