[RxJS] Multicasting shortcuts: publish() and variants

weixin_34067049發表於2016-10-23

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);

 

相關文章