BehaviorSubject vs PublishSubject

后端 未结 4 1325
北海茫月
北海茫月 2021-02-05 01:29

I\'m trying to get my head around the golden rule (if any) about:

When to use BehaviorSubject ?

and

When to

相关标签:
4条回答
  • 2021-02-05 02:08

    PublishSubject: Starts empty and only emits new elements to subscribers. There is a possibility that one or more items may be lost between the time the Subject is created and the observer subscribes to it because PublishSubject starts emitting elements immediately upon creation.

    BehaviorSubject: It needs an initial value and replays it or the latest element to new subscribers. As BehaviorSubject always emits the latest element, you can’t create one without giving a default initial value. BehaviorSubject is helpful for depicting "values over time". For example, an event stream of birthdays is a Subject, but the stream of a person's age would be a BehaviorSubject.

    0 讨论(0)
  • 2021-02-05 02:11

    The main difference between PublishSubject and BehaviorSubject is that the latter one remembers the last emitted item. Because of that BehaviorSubject is really useful when you want to emit states

    Why they make project field a BehaviorSubject and not PublishSubject ?

    Probably because they want to be able to retrieve the last emitted project with this method:

    @Override public @NonNull Observable<Project> project() {
      return this.project;
    }
    
    0 讨论(0)
  • 2021-02-05 02:23

    The difference on BehaviourSubject and PublishSubject relies on how long they keep the data they captures, in instance the PublishSubject only keeps the data available at moment and keeps updating on every entry while BehaviourSubject keeps the last data inserted, so you may use for example to confirm password on a signup form and as an example for PublishSubject, performing a search and it has to update the data constantly in order to give accurate results and there's no too much necessity to compare data that are being inserted.

    As reference i leave this two photos from http://reactivex.io/documentation/subject.html

    PublishSubject

    BehaviourSubject

    0 讨论(0)
  • 2021-02-05 02:25

    Publish Subject: Here, if a student entered late into the classroom, he just wants to listen from that point of time when he entered the classroom. So, Publish will be the best for this use-case.

    Behavior Subject: Here, if a student entered late into the classroom, he wants to listen the most recent things(not from the beginning) being taught by the professor so that he gets the idea of the context. So, here we will use Behavior.

    0 讨论(0)
提交回复
热议问题