码迷,mamicode.com
首页 > Web开发 > 详细

[RxJS] Multicasting shortcuts: publish() and variants

时间:2016-10-23 07:47:30      阅读:321      评论:0      收藏:0      [点我收藏+]

标签:for   span   next   operator   pat   rtc   rtt   with   rod   

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

标签:for   span   next   operator   pat   rtc   rtt   with   rod   

原文地址:http://www.cnblogs.com/Answer1215/p/5988928.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!