如果您运行下面的代码,你会在一个XHR请求,不管我是否是发送控制台中看到subscribed
来subject
。当我不接受该请求时,我不想发出这些请求。
// npm install rxjs
const Rx = require('rxjs/Rx');
let subject = new Rx.BehaviorSubject(null)
Rx.Observable.timer(0, 1000).subscribe(i => someApiCall(i));
//at this point xhr request will be sent every second
function someApiCall(i){
// retrieve some data
console.log("xhr request sent")
subject.next(i);
}
//so here we are gonna subscribe to the subject, xhr made prior
//to this subscription are useless
let subscription;
setTimeout(() => subscription = subject.subscribe(i => console.log(i)),2500);
setTimeout(() => subscription.unsubscribe(),6000);
// now we are unsubscribing but the xhr req keep going
我使用behaviorSubject而不直接在可观察对象上进行订阅的原因是,当我重新订阅时,我希望即时获得最近一次xhr请求中的最后一个值。
https://acutmore.jsbin.com/bepiho/2/edit?js,控制台
const { Observable } = Rx;
function someApiCall(i){
return Observable.create(observer => {
console.log("xhr request sent")
observer.next(i);
observer.complete();
});
}
const data = Rx.Observable.timer(0, 1000)
// map each value to the values of someApiCall
. mergeMap(i => someApiCall(i))
// share the values through a replaySubject
.publishReplay(1)
// Only connect to the source when there is at least one subscriber
.refCount();
data
.take(5)
.subscribe(v => console.log(v));
data
.take(1)
.subscribe(v => console.log(v));
值得一提的是,如果每个人都.take(1)
在订阅时这样做,这将无法按预期工作,因为每个人都将获得中的值ReplaySubject
,然后在做出新的xhrRequest之前立即退订。
即,需要某种东西使其存活足够长的时间,以使发射间隔能够持续进行。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句