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

书接上文

跟大家读一下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的方案

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

以上。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 204,921评论 6 478
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 87,635评论 2 381
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 151,393评论 0 338
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,836评论 1 277
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,833评论 5 368
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,685评论 1 281
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 38,043评论 3 399
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,694评论 0 258
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 42,671评论 1 300
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,670评论 2 321
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,779评论 1 332
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,424评论 4 321
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 39,027评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,984评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,214评论 1 260
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 45,108评论 2 351
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,517评论 2 343

推荐阅读更多精彩内容