[RxJS] Multicasting shortcuts: publish() and variants

Posted Answer1215

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[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);

 

以上是关于[RxJS] Multicasting shortcuts: publish() and variants的主要内容,如果未能解决你的问题,请参考以下文章

SEVERE: Unable to join multicast group, make sure your system has multicasting enabled.

如何理解 RxJS?RxJS的中文API和使用教程

rxjs-tslint vs rxjs-tslint-rules 包

RxJS 6有哪些新变化?

如何在不需要 rxjs-compat 的情况下只导入 RxJS 6 中使用的运算符,如旧的 RxJS?

RxJS入门2之Rxjs的安装