我正在努力实现以下目标:
我有一个可以多次订阅的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;
}
}
假设我在两个不同的地方使用这个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循环中设法使用它? 我一直在研究一个主题/行为主题,但我似乎无法使其发挥作用。
cookies for buts
答案 0 :(得分:0)
我使用以下方法解决了这个问题:
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
答案 1 :(得分:0)
我选择使用简单的Promise,因为我只需要一个多播事件,但是rxjs似乎已经用"Subjects"处理了它
return this.service.add(this.formModel.value, this.imageFile)
.toPromise() // this.subscribe((x) => value = x, (err) => reject(err), () => resolve(value));
.then(id => this.formVm.editMode(id));