zoukankan      html  css  js  c++  java
  • [RxJS] Multicasting shortcuts: publish() and variants

    Because using multicast with a new Subject is such a common pattern, there is a shortcut in RxJS for this: the publish() operator. This lesson introduces publish() and its variants publishReplay(), publishBehavior(), publishLast(), share(), and shows how they simplify the creation of multicasted Observables.

    var shared = Rx.Observable.interval(1000)
      .do(x => console.log('source ' + x))
      .multicast(new Rx.Subject()) 
      .refCount();

    This partten multicast(new Rx.Subject()) to create sharable subject is so common, there is shortcut to doing this: 'publish()':

    var shared = Rx.Observable.interval(1000)
      .do(x => console.log('source ' + x))
      .publish()
      .refCount();

    Also for BehaviourSubject(), AsyncSubject(), ReplaySubject() they all have:

    // publish = multicast + Subject
    // publishReplay = multicast + ReplaySubject
    // publishBehavior = multicast + BehaviorSubject
    // publishLast = multicast + AsyncSubject

    In fact, publish.refCount() is also common used, so there is another alias for this =.=!!

    var shared = Rx.Observable.interval(1000)
      .do(x => console.log('source ' + x))
      .share(); 
    
    // share() == publish().refCount() == multiCast(new Rx.Subject()).refCount()
    var shared = Rx.Observable.interval(1000)
      .do(x => console.log('source ' + x))
      .share();
    
    // share = publish().refCount()
    // publish = multicast + Subject
    // publishReplay = multicast + ReplaySubject
    // publishBehavior = multicast + BehaviorSubject
    // publishLast = multicast + AsyncSubject
    
    var observerA = {
      next: function (x) { console.log('A next ' + x); },
      error: function (err) { console.log('A error ' + err); },
      complete: function () { console.log('A done'); },
    };
    
    var subA = shared.subscribe(observerA);
    
    var observerB = {
      next: function (x) { console.log('B next ' + x); },
      error: function (err) { console.log('B error ' + err); },
      complete: function () { console.log('B done'); },
    };
    
    var subB;
    setTimeout(function () {
      subB = shared.subscribe(observerB);
    }, 2000);
    
    setTimeout(function () {
      subA.unsubscribe();
      console.log('unsubscribed A');
    }, 5000);
    
    setTimeout(function () {
      subB.unsubscribe();
      console.log('unsubscribed B');
    }, 7000);
  • 相关阅读:
    我知道开发已经接近于成功了
    反射获取运行时属性值的替代方法
    Fix Visual Studio 2013 Razor CSHTML Intellisense in Class Library or Console Application
    领域模型
    UI设计心得
    ADO.NET EF 中的实体修改方法
    .net与com组件
    win8设置开机启动项
    编程架构
    禁止UITextField 使用粘贴复制功能
  • 原文地址:https://www.cnblogs.com/Answer1215/p/5988928.html
Copyright © 2011-2022 走看看