美文网首页Rxjs探险之旅
[RXJS探险ep.2] 二向箔asObservable_降维打

[RXJS探险ep.2] 二向箔asObservable_降维打

作者: _老孟_ | 来源:发表于2018-12-13 11:14 被阅读0次

书接上文

跟大家读一下Ben先生的《Converting A Subject To An Observable Using RxJS In Angular 2》

文中提供的代码太老了,老孟会帮大家写成V6版本的。文章就不逐句翻译了,直接上东北大白话:


Converting A Subject To An Observable Using RxJS In Angular 2

标题:在ng里将S变成O(其实和ng没啥关系)

In Angular 2, you can use the Rx.Subject class to create the source of an observable sequence. But, you never want to return an Rx.Subject instance to the calling context. Doing so would be somewhat akin to returning a Deferred object rather than a promise; and, it would leave the Subject open to unanticipated and corrupting usage. As such, when exposing a Subject, you'll probably want to convert it to an Observable first.

诚然你可以用S创造数据序列,但这样做不好,原因如下:

  1. 会返回一个延迟对象而不是承诺(这句以后展开说)
  2. 君子不立危墙之下,S的Observable &Observer双重身份是一种特色,也是带来了风险,把S暴漏给执行上下文容易导致混乱。

所以要想办法把S变成O。

Up until now, as a newcomer to RxJS, I've been trying to do this - converting a Subject to an Observable - using the Rx.Observable.from() creation method. Unfortunately, while it appeared as if it was working (in the way that I intended), it actually was not. To demonstrate, we're going to use Rx.Observable.from() to try and convert a Subject to an Observable and then test whether or not we can call the .next() method on the result (if all goes well, we shouldn't be able to):

Ben先生试图用from对Subject进行包装,然而这种方式是错的。代码如下:

//老孟翻译成了V6版本
    const getObservable = (): any => {
      const  source = new Subject();
      setInterval(
          function emitNextValue() {
              source.next( new Date().getTime() );
          },
          1000
      );
      return( from(source));//试图用from把S包装成O
  };
    const stream = getObservable();
    stream.pipe(
      take( 3 )
    ).subscribe(
      (value)=>console.log('Observable value:'+value)
    );

    try {
        stream.next( 'foo' );
        console.warn( "Not good! You were able to call .next() on the stream." );
    } catch ( error ) {
        console.log( "Thank goodness! You weren't able to call .next() on the stream." );
    }
结果: convert-subject-to-observable-rxjs-from.png

As you can see, we were able to invoke the .next() method on the returned value which means that we accidentally returned the Subject back to the calling context. In essence, the Rx.Observable.from() method didn't do anything. And, in fact, if you look at the RxJS source code, you will see that this method will simply pass-through the given object if it is already an instance of the Observable class (which, of course, Subject is by way of inheritance).
The reason that I thought this was working was because the resultant value acts like an Observable. But, that's only because Subject is already an Observable.
So, basically, I've been wrong up until now (and will try to go back and correct some code).

如你所见,from这招不靠谱,next依然暴漏在外。这是因为:如果from接收了一个Observable 的实例(包括S),会单纯的把它传递出去。具体看源码。Ben先生顺便吐槽了一下自己。

To get this working in the way that we actually intended it to, we can use the Rx.Observable.prototype.asObservable() instance method. I actually saw this method a while back, but the description didn't make sense to me at the time:

asObservable则可以解决这个问题,官网的描述如下:

Hides the identity of an observable sequence.
隐藏O的特征

Why would I ever want to "hide" the identity of an observable? Seems like such an odd gesture. Until you remember that other classes can extend Observable. Then, it starts to make a little bit more sense. Though, I might rephrase it to be something like:

Ben先生觉得描述得不好并吐槽了一下官网,自己给了个版本

(Ben's version) Casts any object that implements the observable interface into a new Observable instance.
将实现了observable 接口的对象变成成新的O。

any object that implements the observable interface?老孟觉得这个解释有点问题,asObservable不只是S的方法吗?暂时不深究。

查了一下官网,现在描述变了:

Creates a new Observable with this Subject as the source. You can do this to create customize Observer-side logic of the Subject and conceal it from code that uses the Observable.

说的云山雾绕...我不翻译了,下面是老孟的理解:


    const myS = new Subject();
    const myO= myS.asObservable();

myS还是Subject,依然保留Observable & Observer双重身份,myO是myS通过asObservable创造出来单纯的Observable,抛弃了Observer的特征, 这就是我标题里提的降维打击!!。通过这种方式,可以把myO暴漏出去提供订阅,毕竟单纯的Observable更健壮,myS得到了保护,不再用抛头露面了。

我再吐槽一次,asObservable这个方法太隐蔽了。如果没有高人指点,老孟真不知道何年马月才能注意到。


Ben先生将from改成了asObservable:

//老孟翻译成了V6版本
    const getObservable = (): any => {
      const  source = new Subject();
      setInterval(
          function emitNextValue() {
              source.next( new Date().getTime() );
          },
          1000
      );
      return( source.asObservable());//就改了这一块儿
    };

    const stream = getObservable();
    stream.pipe(
      take( 3 )
    ).subscribe(
      console.log
    );

    try {
        stream.next( 'foo' );
        console.warn("Not good! You were able to call .next() on the stream." );
    } catch ( error ) {
        console.log( "Thank goodness! You weren't able to call .next() on the stream."  );
    }

结果:


convert-subject-to-observable-rxjs-as-observable.png

As you can see, when we tried to call .next() on the returned value, an error was thrown. This is because we successfully converted the Subject instance to an Observable instance, shielding the calling context from the Subject implementation.
While you can technically pass around instances of Subject, doing so allows implementation details to bleed into other parts of the application. To prevent this, it is best to convert Subjects to Observables so that the sequence is exposed in a read-only fashion. Luckily, this is quite easy to accomplish with the .asObservable() instance method inherited by the Subject class in RxJS.

如你所见,生效了,不再能next()了,建议大家使用这招儿。

回顾问题,总结一下

  1. 乱用命令式的S会有带来怎样的具体问题?

答:风险大,不可靠,S是用来多播的,语义上也容易有歧义

  1. asObservable是个啥?(语义上来看应该是将S视为O)
  2. 如何用O代替S(其实大哥想表达的意思是:如何将S变成O)?

答:问题2是解决问题3的方案

累了这么久就总结出这点玩意儿......如果写的有错误,请及时告诉老孟

以上。

相关文章

  • [RXJS探险ep.2] 二向箔asObservable_降维打

    书接上文 跟大家读一下Ben先生的《Converting A Subject To An Observable U...

  • 降维打击

    降维打击这个概念来源于刘慈欣科幻小说《三体世界》中,里面有个“二向箔”的东西可以把所有接触者从三维降维到二维,...

  • 【小思考】重新理解降维

    其实是, 从旧理解降维。 1 二向箔 我们贯常所说的“降维(攻击)”源于《三体》,那摄人心魄的一幕。 歌者弹向太阳...

  • 降维攻击,究竟是从什么时候开始的?

    ——闲话三体之九 一 小说里的降维攻击 大刘最具诗意也是最牛逼的脑洞,是二向箔降维攻击。 但大刘肯定没有想到,降维...

  • 2019-02-07世界是否在降维?

    关键词降维风险:刘慈欣在三体中讲到了降维,高等级文明用一根二向箔,就把太阳系从三维世界降成了二维,席卷,推平。 思...

  • 2018-12-18知识管理中的“二向箔”

    2018-12-18知识管理中的“二向箔” 2018年12月18日 13:09:35 降维打击是小说《三体》中外星...

  • 《三体》刘慈欣

    看三体,源于一个十分钟视频,几句牛气冲天的话:二向箔二维展开,降维攻击,毁灭你,与你何干? 看书,文字平庸,行文并...

  • 《三体》《星空》

    这就是梵高的名画《星空》,《三体》作者描述的被二向箔降维攻击的二维化太阳系,灵感无疑来自于这幅印象派画作。 画中没...

  • 苑九芬1860:改变固有认知

    《三体》一书中,有个词叫“降维打击”。 本是指外星人使用“二向箔”,将太阳系由三维空间降至二维空间的一种攻击方式。...

  • 人与人最大的差距:认知层次

    《三体》一书中,有个词叫“降维打击”。 本是指外星人使用“二向箔”,将太阳系由三维空间降至二维空间的一种攻击方式。...

网友评论

    本文标题:[RXJS探险ep.2] 二向箔asObservable_降维打

    本文链接:https://www.haomeiwen.com/subject/uvyvhqtx.html