BehaviorSubject needs to be created with a default initial value
When a subscriber comes to subscribe to it, the subscriber will immediately receive the last event emitted by BehaviorSubjects. After that, just like the normal situation, it will also receive new events issued after BehaviorSubject
//Create a BehaviorSubject
let subject = BehaviorSubject(value: "111")
//Subscribe for the first time subject
subject.subscribe {event in
print("The first subscription:", event)
}.disposed(by: disposeBag)
BehaviorRelay appears as a replacement for Variable. Its essence is actually the encapsulation of BehaviorSubject, so it must also be created by a default initial value
BehaviorRelay has the function of BehaviorSubject, which can send the last event and the newly created event to its subscribers
Unlike BehaviorSubject, BehaviorRelay will automatically send a .complete event when it is destroyed, and you can’t manually and completely send completed or error events to BehaviorReply to end it.
BehaviorRelay has a value attribute, through which we can get the latest value. The value can be modified through its accept() method
//Create a BehaviorRelay with an initial value of 111
let subject = BehaviorRelay<String>(value: "111")
//Modify value
subject.accept("222")
//The first subscription
subject.asObservable().subscribe {
print("1st subscription:", $0)
}.disposed(by: disposeBag)
//Modify value
subject.accept("333")
If you want to merge the new value to the original value, you can use the accept() method in conjunction with the value attribute. (This is commonly used in the form of pull-up loading function, BehaviorRelay is used to save all loaded data)