Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When to use Subject, BehaviorSubject with real example

Tags:

angular

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.

like image 698
user54226 Avatar asked Dec 04 '22 18:12

user54226


1 Answers

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?

like image 66
Harun Yilmaz Avatar answered Jan 15 '23 16:01

Harun Yilmaz