6

I'm studying Angular, and currently I'm on the topic of Observables. I now understand what are Observables including Subject, BehaviorSubject, ReplaySubject. But I need a real world example where these can be practically implemented with difference so I can understand when to use which method.

For example, any application in which I can see/compare the implementation of above methods.

user54226
  • 77
  • 1
  • 3
  • 10

4 Answers4

20

You use BehaviorSubject instead of Subject when you want to have an initial (default) value from the stream.

Let's suppose you want to check if the user logged in:


with Subject

isLoggedIn$ = new Subject<boolean>();

.........

isLoggedIn$.subscribe(res => console.log(res))

This subscribe will not fire until isLoggedIn$.next(someValue) is called.


But with BehaviorSubject

isLoggedIn$ = new BehaviorSubject<boolean>(false); // <---- You give 'false' as an initial value

.........

isLoggedIn$.subscribe(res => console.log(res))

This subscribe will fire immediately as it holds false as a value in stream.


So if you want an initial (default) value, you need to use BehaviorSubject.

https://medium.com/@luukgruijs/understanding-rxjs-behaviorsubject-replaysubject-and-asyncsubject-8cc061f1cfc0

What is the difference between Subject and BehaviorSubject?

Harun Yilmaz
  • 8,281
  • 3
  • 24
  • 35
  • So for your example, should we use Subject or BehaviorSubject? Why? – William Nov 30 '22 at 21:44
  • Hello, @William I think I answered why/when with the reasonings above. Do you have a specific use case? – Harun Yilmaz Dec 01 '22 at 07:23
  • thanks @Harun. i've read your answer again. if you need to check a user logged in or not, should you use subject or behaviorsubject? – William Dec 01 '22 at 08:59
  • 1
    @William If you want to have an initial (default) value for user login info, let's say the default is `false`, then it's better to have `BehaviorSubject`. – Harun Yilmaz Dec 01 '22 at 09:14
5

Here is a practical example and little explanation. let's say you have an application with many components e.g.: shopping cart , you have a navigation bar showing items added to the cart. you have products page, grid of items with many add to cart button. product detail page where you have one add to cart button for that product. and finally the order summary page(i.e. the cart page where you have buttons against each product in the list to add + or remove -. In the above scenario you can use Subjects or BehaviorSubject on the cartService. and all other components subscribing to it via service dependency injection. The add to cart button will invoke the next() function of the service. In case you want the cart to be pre-populated from the browser local storage (or other mechanism) when the user has left the session by just selecting the items into the cart but did not complete the transaction process. You may use BehaviorSubject to do that initial load to cart.

To extend what @Harun Yilmaz wrote, user logged in status had to be checked from different part of the single page application in that case you can use accordingly, to check if the login status of the user is still valid.

Do not get confused with web streaming and message streaming. message streaming works in conjunction with streams of events. please don't get it wrong. eg: web streaming is where you eg: socket where you make a connection first and then exchange packets of data like streaming.

In angular too it works similar you make a connection by subscribing to the asObservable(). exchange data like streams of message. A BehaviorSubject sends you a welcome message while subject do not send any message until next() is called

You go to a restaurant and the waiter greets you proactively BehaviorSubject waiter greets (how may i help you) you when you call Subject all waiters on the floor are providing service subscribed by the restaurant owner.

hope this helps to understand

UPDATED on 22/06/2020

above mentioned topics are related to reactive programming. which means the application shroud react to a event. events can default browser events like click mouesevent or any custom event that can be emitted. eg. when user do add to cart, place order. It is called reactive because events are uncertain and we do not know when it is going to happen. eg. you subscribe to a youtube channel because you don't know when the creator will post a new video, so you set a kind of event watcher. which will constantly look for that event to occur.

so if i create a sample single page youtube application with no server involved. You will have a creatorcomponent , viewercomponent , publishService. when the creator publishes a video or releases it, it calls the publishService and wires a message 'new_video_published' who ever are subscribing to this creator will receive the notification and viewerComponent gets to know it.

now if the publishService uses a BehaviorSubject to do the message passing the new subscriber (viewer) will immediately get the latest video released by that creator. If the punlishService uses Subject the new subscriber will not get any immediate message but all messages going forward.

publish.service.ts

... other code ...

    subscribeMes$ = new Subject<string>(); 
    //OR
    //subscribeMeb$ = new BehaviorSubject<string>('Welcome Message'); 



newPublish(srting) {
        this._name.next(string);
      }

viewer.component.ts

   //injecting service
subscribedOn_21022020(){
    this.publishService.subscribeMes$.subscribe(n=>{
     this.newVideo =n
    })
}

subscribedOn_23022020(){
    this.publishService.subscribeMes$.subscribe(n=>{
     this.newVideo = n
    })
}

creator.component.ts

this.publishService.newPublish('new video on Rxjs on 22/02/20')

in the above sample we see that when the application first loads on 21-02-2020 in the browser as there no video published(hypothetical event scenario) . the subscribedOn_21022020() will not receive any welcome message when the publish.service.ts uses Subject. In case BehaviorSubject was used they would have received the Welcome message. On 22/02/2020 the creator publishes a video so the subscribedOn_21022020() will receive the new video message ,( in case of BehaviorSubject it would have been be his second message). Now on 23-02-2020 a second user subscribe subscribedOn_23022020() today he will not receive any message immediately but will get new video publish notification anytime in the future as the publish service uses Subject. In case BehaviorSubject was used the second subscriber would have got the 'new video on Rxjs on 22/02/20' message immediately after subscription. and continue to get future videos.

Srijib Mandal
  • 585
  • 6
  • 12
0

I used behavior subject for sending message between parent and child component and between sibling component.

This is sample for behavior subject, it may help you https://stackblitz.com/edit/behavior-subject-2019

Hien Nguyen
  • 24,551
  • 7
  • 52
  • 62
  • Thanks, but I wish to see a real time application example, say, a website where users can live stream the score or any other example. From that Live example I think I can better understand the concepts. – user54226 Mar 29 '19 at 07:50
0

Behavior subject can be used when you have an initial value. If you are using authService and wanna have initial value as 'null', we use BehaviorSubject.

We cannot use Subject, because subject is hot in nature. That means it is going to emit values even if someone is not listening. That means if we start to subscribe to the subject too late after an event has been emitted, we are not gonna receive that event.

We need to make sure, the instant that components subscribe, they are told whatever the latest value was emitted. That is why we use BehaviorSubject, because it emits the latest value, when a component subscribes.

Yilmaz
  • 35,338
  • 10
  • 157
  • 202