Swift Combine: PassthroughSubject! Define your event with PassthroughSubject Top iOS Dev Techniques
--
Combine comes with useful subjects that help you write code easier! You must learn them very carefully! For those who don’t know about Subject
, just think it as an object that can send data with a stream.
Publisher that you can continuously send new values down.
Core Functionalities of PassthroughSubject
- Subscribe to Subject
- Passing down new values with Subject
- Sending completion finished with Subject
PassthorughSubject and its main characteristics
PassthroughSubject is a Generic Type. The first Generic Type is the data that PassthroughSubject will have. The second Generic Type is for Error. You can use Never
under the assumption that an Error will never occur.
Unlike CurrentValueSubject
, PassthroughSubject doesn’t have any value. Therefore, you can’t use passthroughSubject.value
syntax. It simply does not exist.
So PassthroughSubject
is mostly used for Event
.
[1] Subscribe to Subject
Like any other publisher in Combine Framework, you can subscribe to PassthroughSubject by calling .sink
method.
[2] Passing down new values with Subject
You can send data with PassthroughSubject. Remember this statement?
Publisher that you can continuously send new values down.
This is it.
[3] Sending completion finished with Subject
By sending completion
with .finished
, you can stop any event from happening.
Conclusion
- Subscribe to Subject
- Passing down new values with Subject
- Sending completion finished with Subject