我正在努力实现以下目标:
我有一个可多次订阅的Observable,尽管我只想进行一次处理。
export class DataLoader
{
private loaded = false;
private data: Data;
private observable = null;
load(): Observable<Data> {
if(this.loaded) {
console.log('Already loaded');
return Observable.create((obs) => {
obs.next(this.data);
obs.complete();
})
}
if(this.observable === null) {
console.log('Creating observable');
this.observable = Observable.create((obs) => {
console.log('firing xhr');
let xhr;
xhr.onload = () => {
this.data = data;
this.loaded = true;
obs.next(data);
obs.complete();
this.observable = null;
}
xhr.onerror = () => {
obs.error(error);
this.observable = null;
}
});
}
return this.observable;
}
}
可以说我在2个不同的地方使用此DataLoader,“ xhr”将只执行一次。
...
Dataloader.load().subscribe();
...
#At another point in the code
Dataloader.load().subscribe();
...
安慰:
Creating observable
firing xhr
Already Loaded
只要请求之间的触发时间不会太短,此方法就可以正常工作。
为了演示,将其放入for循环中:
for(let i = 0; i<10; i++) {
DataLoader.load().subscribe();
}
在这种情况下,控制台如下所示:
Creating observable
firing xhr
firing xhr
firing xhr
firing xhr
firing xhr
firing xhr
firing xhr
firing xhr
firing xhr
firing xhr
我如何在for循环中使用它?
我一直在研究Subject / BehaviourSubject,但似乎无法使其正常工作。
曲奇
最佳答案
我使用以下方法解决了它:
if(this.observable === null) {
console.log('Creating observable');
let source = Observable.create((obs) => {
console.log('firing xhr');
let xhr;
xhr.onload = () => {
this.data = data;
this.loaded = true;
obs.next(data);
obs.complete();
this.observable = null;
}
xhr.onerror = () => {
obs.error(error);
this.observable = null;
}
});
let subject = new Subject();
this.observable = source.multicast(subject);
this.observable.connect();
}
http://reactivex.io/rxjs/manual/overview.html#multicasted-observables
关于javascript - 多次订阅可观察的rxjs,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/40863280/