ReplaySubject will maintain and replay a buffer of the size you specify of the latest next events in the order they were emitted. To create a ReplaySubject, you need to explicitly declare a type because the initializer does not take an initial value, so it can't infer the type and use the create(bufferSize:) static convenience method to pass the number of elements you want replayed to new subscribers for the bufferSize parameter. Similar to the last section, we will start this section with a basic code setup and build on top of the previous example by just commenting out the sample code for BehaviorSubject:
executeProcedure(for: "ReplaySubject"){
let disposeBag = DisposeBag()
}
Then, to this basic implementation we will add the instance of ReplaySubject, as follows:
let repSubject = ReplaySubject<String>.create(bufferSize: 3)
This subject will replay the last three elements. Next, we will add three elements onto the subject:
repSubject.onNext("First")
repSubject.onNext("Second")
repSubject.onNext("Third")
Then, we will create the onNext subscription, printing out each element as it is emitted:
repSubject.subscribe(onNext: {
print($0)
})
.disposed(by: disposeBag)
On monitoring the output in console, we will see that all three elements are printed:
Now we will add another element to the subject before the subscription:
repSubject.onNext("First")
repSubject.onNext("Second")
repSubject.onNext("Third")
repSubject.onNext("Fourth")
repSubject.subscribe(onNext: {
print($0)
})
.disposed(by: disposeBag)
Check the output; you will see that still only the last three next elements are replayed and hence printed:
Now add another value, this time after the subscription; that element is emitted and printed by itself after the buffer that was printed upon subscription:
repSubject.subscribe(onNext: {
print($0)
})
.disposed(by: disposeBag)
repSubject.onNext("Fifth")
It will give the following output:
A ReplaySubject will emit each element as it's added on to the sequence after subscription. It only replays its whole buffer to its new subscribers.
Let's create a new subscription, once again differentiating it by prefixing New Subscription in the print statement:
repSubject.subscribe(onNext: {
print("New Subscription: ", $0)
})
.disposed(by: disposeBag)
The new subscription only gets the last three buffered elements that are replayed, which you can see in the output:
Consolidated code for the ReplaySubject in this example will be as follows:
executeProcedure(for: "ReplaySubject"){
let disposeBag = DisposeBag()
let repSubject = ReplaySubject<String>.create(bufferSize: 3)
repSubject.onNext("First")
repSubject.onNext("Second")
repSubject.onNext("Third")
repSubject.onNext("Fourth")
repSubject.subscribe(onNext: {
print($0)
})
.disposed(by: disposeBag)
repSubject.onNext("Fifth")
repSubject.subscribe(onNext: {
print("New Subscription: ", $0)
})
.disposed(by: disposeBag)
}