Here is few finding and analysis about the topics for above topics,
BehaviorSubject is a type of subject, a subject is a special type of observable so you can subscribe to messages like any other observable. The unique features of BehaviorSubject are:
- It needs an initial value as it must always return a value on subscription even if it hasn't received a
next()
- Upon subscription, it returns the last value of the subject. A regular observable only triggers when it receives an
onnext
- at any point, you can retrieve the last value of the subject in a non-observable code using the
getValue()
method.
Unique features of a subject compared to an observable are:
- It is an observer in addition to being an observable so you can also send values to a subject in addition to subscribing to it.
In addition, you can get an observable from behavior subject using the
asObservable()
method on BehaviorSubject
.
Observable is a Generic, and
BehaviorSubject
is technically a sub-type of Observable because BehaviorSubject is an observable with specific qualities.
Observe how using
Observable.create
created different output for each observer, but BehaviorSubject
gave the same output for all observers. This is important.
Other differences summarized.
━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓
┃ Observable ┃ BehaviorSubject/Subject ┃
┣━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━╋━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┫
│ Is just a function, no state │ Has state. Stores data in memory │
├─────────────────────────────────────┼─────────────────────────────────────┤
│ Code run for each observer │ Same code run │
│ │ only once for all observers │
├─────────────────────────────────────┼─────────────────────────────────────┤
│ Creates only Observable │Can create and also listen Observable│
│ ( data producer alone ) │ ( data producer and consumer ) │
├─────────────────────────────────────┼─────────────────────────────────────┤
│ Usage: Simple Observable with only │ Usage: │
│ one Obeserver. │ * Store data and modify frequently │
│ │ * Multiple observers listen to data │
│ │ * Proxy between Observable and │
│ │ Observer │
└─────────────────────────────────────┴───────────────
Feel free to ask your queries and comments.
No comments:
Post a Comment