Return 在发出事件之前可观察
Return observable before emitting event
我创建了一个函数,如果它在内存中没有对象,它会在返回之前获取它。
然而,当它在内存中时,它会在允许订阅者订阅事件之前立即发出。
为了解决这个问题,我在下面的示例中添加了一个 setTimeout,但我觉得它是 hacky。
问题是,有没有更好的方法(最佳实践)来解决这个问题?
itemSubject = new Subject<T[]>();
getAll(): Observable<T[]> {
if (this.snapshot) {
setTimeout(() => { //this is what i am trying to replace.
this.itemSubject.next(this.snapshot)
}, 0);
}
else {
this.load().subscribe(
(res) => {
this.snapshot = (<any>res).data
this.itemSubject.next(this.snapshot);
}
);
}
return this.itemSubject.asObservable();
}
最终使用 Rxjs of
。
要了解更多信息,请访问:LearnRxJS.io
itemSubject = new Subject<T[]>();
getAll(): Observable<T[]> {
if (this.snapshot) {
return of(this.snapshot); // requires rxjs library
//setTimeout(() => {
// this.itemSubject.next(this.snapshot)
//}, 0);
}
else {
this.load().subscribe(
(res) => {
this.snapshot = (<any>res).data
this.itemSubject.next(this.snapshot);
}
);
}
return this.itemSubject.asObservable();
}
我创建了一个函数,如果它在内存中没有对象,它会在返回之前获取它。
然而,当它在内存中时,它会在允许订阅者订阅事件之前立即发出。
为了解决这个问题,我在下面的示例中添加了一个 setTimeout,但我觉得它是 hacky。
问题是,有没有更好的方法(最佳实践)来解决这个问题?
itemSubject = new Subject<T[]>();
getAll(): Observable<T[]> {
if (this.snapshot) {
setTimeout(() => { //this is what i am trying to replace.
this.itemSubject.next(this.snapshot)
}, 0);
}
else {
this.load().subscribe(
(res) => {
this.snapshot = (<any>res).data
this.itemSubject.next(this.snapshot);
}
);
}
return this.itemSubject.asObservable();
}
最终使用 Rxjs of
。
要了解更多信息,请访问:LearnRxJS.io
itemSubject = new Subject<T[]>();
getAll(): Observable<T[]> {
if (this.snapshot) {
return of(this.snapshot); // requires rxjs library
//setTimeout(() => {
// this.itemSubject.next(this.snapshot)
//}, 0);
}
else {
this.load().subscribe(
(res) => {
this.snapshot = (<any>res).data
this.itemSubject.next(this.snapshot);
}
);
}
return this.itemSubject.asObservable();
}