Observable, Subject & BehaviorSubject
Difference Between Observable and Subject
If all you are concerned about is data retrieval then DeborahK's answer is pretty much right on. Typically, and I say "typically" lightly, an HTTP request is a standard observable, meaning the request goes out, comes back, returns some data, and doesn't get fired again until a new subscription is made to it. For most observable patterns, the standard Observable
type is perfect for the job.
The easiest way to think about it is to just look at the name; Observable. If all you are doing is 'getting' data, then an Observable
is what you want. However, if you find that you have a requirement to manipulate the stream of data after instantiation, then a Subject
or BehaviorSubject
may be the right fit. The difference between Subject
and BehaviorSubject
is that a Subject
does have to have an initial value, where a BehaviorSubject
is given an initial value on instantiation.
A good example of a use case for a Subject
or BehaviorSubject
is a boolean value that is used across a site to tell the application when a Modal should be visible or not. Since multiple components can alter the state of the visibility of the Modal, you would need a BehaviorSubject
that can be altered, triggering the parent component to display the modal.
Another good example for Subject
would be a search bar that advertises it's contents to other components throughout the application. The key here is that you are emitting new values to the stream to be observed by other components/services within the application.
The last thing I will say about is that all of the above fall under the category of an Observable
, technically speaking. I think that's where a lot of the confusion takes place.
Pushing Data
Another thing I am noticing about your question is that seems like you are actually trying to solve a problem that isn't necessarily solvable within Angular itself. If you have very dynamic data within your "backend" that you want to be pushed out to your front end, then you may need to look into a websocket socket server. It sounds way more complicated than it is, but essentially it allows your server to "push" data to your application. If it's secure data, I recommend using your server to push an "updates available" message, and then have the application securely make an HTTP request for the updated data. DO NOT send secure information over web sockets. Here is a great resource for websockets using Socket IO within a node server and making pushes to an Angular App. There's a lot out there.