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.
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?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With