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

[RXJS探险ep.2] 二向箔asObservable_降维打击_第1张图片

书接上文

跟大家读一下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." );
    }

结果:
[RXJS探险ep.2] 二向箔asObservable_降维打击_第2张图片
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."  );
    }

结果:


[RXJS探险ep.2] 二向箔asObservable_降维打击_第3张图片
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_降维打击)