11

I am aware that BehaviorRelay is replacing Variable, and both BehaviorSubject and BehaviorRelay starts with an initial value, and replays it or the latest value to the subscribers.

What are the differences then? in which case you would use one over the other?

Alan Steiman
  • 412
  • 1
  • 4
  • 14
  • 3
    Maybe [this](https://medium.com/@dimitriskalaitzidis/rxswift-subjects-a2c9ff32a185) will help. – Sweeper Jul 17 '20 at 01:33

2 Answers2

17

As stated in the source file for BehaviorRelay:

BehaviorRelay is a wrapper for BehaviorSubject.

Unlike BehaviorSubject it can't terminate with error or completed.

You would then use BehaviorSubject to model a stream that might terminate with and error, while BehaviorRelay will give the guarantee to the users of your api that no error can come from it.

tomahh
  • 13,441
  • 3
  • 49
  • 70
  • 5
    That should read "You would then use BehaviorSubject to model a stream that might terminate. (full stop)". Subjects can terminate, Relays never terminate. – Daniel T. Jul 17 '20 at 11:17
7

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)

Tema Tian
  • 331
  • 3
  • 12