首页 > 代码库 > [RxJS] Multicasting shortcuts: publish() and variants
[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 + AsyncSubjectvar 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
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。