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);
  • 相关阅读:
    【leetcode-100】 简单 树相关题目
    【leetcode-101】 对称二叉树
    【2】【leetcode-105,106】 从前序与中序遍历序列构造二叉树,从中序与后序遍历序列构造二叉树
    【leetcode-102,107,103】 二叉树的层次遍历
    iOS开发
    对称加密和不对称加密原理
    uiimageview 异步加载图片
    如何让IOS中的文本实现3D效果
    SDWebImage使用,图片加载和缓存
    ios 图片处理( 1.按比例缩放 2.指定宽度按比例缩放
  • 原文地址:https://www.cnblogs.com/Answer1215/p/5988928.html
Copyright © 2011-2022 走看看