什么时候在 rxjs 中使用 asObservable()? [英] When to use asObservable() in rxjs?

查看:35
本文介绍了什么时候在 rxjs 中使用 asObservable()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道 asObservable:

根据文档:

隐藏身份的可观察序列源序列.

An observable sequence that hides the identity of the source sequence.

但是为什么需要隐藏序列?

But why would you need to hide the sequence?

推荐答案

何时使用 Subject.prototype.asObservable()

这样做的目的是为了防止泄露观察者端"从 API 中提取主题.基本上是为了在您不希望人们能够下一步"时防止抽象泄漏.转化为结果 observable.

When to use Subject.prototype.asObservable()

The purpose of this is to prevent leaking the "observer side" of the Subject out of an API. Basically to prevent a leaky abstraction when you don't want people to be able to "next" into the resulting observable.

(注意:这真的不是你应该如何将这样的数据源变成 Observable,而是你应该使用 new Observable 构造函数,见下文).

(NOTE: This really isn't how you should make a data source like this into an Observable, instead you should use the new Observable constructor, See below).

const myAPI = {
  getData: () => {
    const subject = new Subject();
    const source = new SomeWeirdDataSource();
    source.onMessage = (data) => subject.next({ type: 'message', data });
    source.onOtherMessage = (data) => subject.next({ type: 'othermessage', data });
    return subject.asObservable();
  }
};

现在,当有人从 myAPI.getData() 获得可观察的结果时,他们不能next 值到结果中:

Now when someone gets the observable result from myAPI.getData() they can't next values in to the result:

const result = myAPI.getData();
result.next('LOL hax!'); // throws an error because `next` doesn't exist

你通常应该使用 new Observable(),不过

在上面的示例中,我们可能正在创建我们不想要的东西.一方面,getData() 不像大多数 observable 那样懒惰,它会立即创建底层数据源 SomeWeirdDataSource(可能还有一些副作用).这也意味着如果你 retryrepeat 得到的 observable,它不会像你想象的那样工作.

You should usually be using new Observable(), though

In the example above, we're probably creating something we didn't mean to. For one, getData() isn't lazy like most observables, it's going to create the underlying data source SomeWeirdDataSource (and presumably some side effects) immediately. This also means if you retry or repeat the resulting observable, it's not going to work like you think it will.

最好像这样将数据源的创建封装在 observable 中:

It's better to encapsulate the creation of your data source within your observable like so:

const myAPI = {
  getData: () => return new Observable(subscriber => {
    const source = new SomeWeirdDataSource();
    source.onMessage = (data) => subscriber.next({ type: 'message', data });
    source.onOtherMessage = (data) => subscriber.next({ type: 'othermessage', data });
    return () => {
      // Even better, now we can tear down the data source for cancellation!
      source.destroy();
    };
  });
}

使用上面的代码,任何行为,包括使它不懒惰"可以使用 RxJS 现有的操作符在 observable 之上进行组合.

With the code above, any behavior, including making it "not lazy" can be composed on top of the observable using RxJS's existing operators.

这篇关于什么时候在 rxjs 中使用 asObservable()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆