I am wondering what is the use of asObservable
:
As per docs:
An observable sequence that hides the identity of the source sequence.
But why would you need to hide the sequence?
When you don't want to leak the "observer-side" of a Subject
out of your API. (Basically to prevent leaky abstraction).
var myAPI = {
getData: () => {
var subject = new Subject();
var source = new SomeWeirdDataSource();
source.onMessage = (data) => subject.next({ type: 'message', data });
source.onOtherMessage = (data) => subject.next({ type: 'othermessage', data });
return subject.asObservable();
}
};
Now when someone gets the observable result from myAPI.getData()
they can't next
values in to the result:
var result = myAPI.getData();
result.next('LOL hax!'); // throws an error because `next` doesn't exist
来源:https://stackoverflow.com/questions/36986548/when-to-use-asobservable-in-rxjs