When to use asObservable() in rxjs?

生来就可爱ヽ(ⅴ<●) 提交于 2019-11-27 06:29:29

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
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!