首页 > 代码库 > [RxJS] RefCount: automatically starting and stopping an execution
[RxJS] RefCount: automatically starting and stopping an execution
With the connect() method on a ConnectableObservable, the programmer is responsible for avoiding leaked executions of shared RxJS Observables. This lesson will teach you about refCount(), a handy operator that creates an automatically connected Observable, to avoid manually using connect().
After multicast(new Rx.Subject()), we call refCount(), so it will help us to manage the connections, so we don‘t need to worry about the memory leak.
var shared = Rx.Observable.interval(1000) .do(x => console.log(‘source ‘ + x)) .multicast(new Rx.Subject()) .refCount();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); // startvar 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); // 1 => 2}, 2000);setTimeout(function () { subA.unsubscribe(); // 2 => 1 console.log(‘unsubscribed A‘);}, 5000);setTimeout(function () { subB.unsubscribe(); // 1 => 0 (stop) console.log(‘unsubscribed B‘);}, 7000);/*"source 0""A next 0""source 1""A next 1""source 2""A next 2""B next 2""source 3""A next 3""B next 3""source 4""A next 4""B next 4""unsubscribed A""source 5""B next 5""source 6""B next 6""unsubscribed B"*/
[RxJS] RefCount: automatically starting and stopping an execution
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。