RxSwift: Subjects
In this blog, I will talk about subjects & variables in RxSwift. I hope you must be knowing about RxSwift. If you don’t then read my earlier blog https://medium.com/@arnavgupta180/shift-from-swift-to-rxswift-8dece8af9f4 for better understanding of concepts of RxSwift.
Subjects
A Subject is a sort of bridge or proxy that acts both as an observer and as an Observable. A subject can emit it’s elements even if it has no observers.
Subject Types
There are three commonly used subject types. They all behave almost the same with one difference: each one does something different with values emitted before the subscription happened.
Publish Subject :
the publish subject will ignore all elements that were emitted before subscribe
have happened.
Replay Subject :
Replay subject will repeat the last N number of values, even the ones before the subscription happen. The N is the buffer, so for our example it’s 3.
Behavior Subject :
Behavior subject will repeat only the one last value. Moreover, it’s initiated with a starting value, unlike the other subjects.
Example
let subject = defined below with output w.r.t all cases of subjects.
let observable : Observable<String> = subject subject.onNext("Before Subscribe Value First")
subject.onNext("Before Subscribe Value Second")
subject.onNext("Before Subscribe Value Third")observable.subscribe(onNext: { text in
print(text)
}).addDisposableTo(disposeBag) subject.onNext("After Subscribe")
OUTPUT
Output1) PublishSubject
let subject = PublishSubject<String>()
Output:
After Subscribe //no values repeat before subscibe
2) ReplaySubject with buffer size 3let subject = ReplaySubject<String>().create(bufferSize: 3) Output:Before Subscribe Value First //on subscribe will repeat buffer
Before Subscribe Value Second // size value eg last 3
Before Subscribe Value Third
After Subscribe
3) BehaviorSubject : It has initial valuelet subject = BehaviorSubject<String>(value: "Initial value") Output:Before Subscribe Value Third //on subscribe will repeat last value
After Subscribe