我有以下重试逻辑来重试操作。它适用于单个请求。对于多个正在进行的请求,我想在重试之前等待现有的重试逻辑完成。
handleError(errors: Observable<any>) {
const retryCountStart: number = 1;
// wait if there is any existing operation retrying
// once it is complete, continue here
return errors
.mergeScan<any, any>(
(retryCount: any, err: any) => {
if (retryCount <= 5) {
return Observable.of(retryCount + 1);
}
},retryCountStart)
.delay(1000);
}
如何在上述方法中满足某些条件之前添加延迟?
答案 0 :(得分:0)
您可以将async
/ await
用于Promise解决方案:
async handleError(errors: Observable<any>) {
const retryCountStart: number = 1;
// wait if there is any existing operation retrying
// ----------------------------------------------------------
await new Promise(resolve => {
// declare some global variable to check in while loop
while(this.retrying){
setTimeout(()=> {
// Just adding some delay
// (you can remove this setTimeout block if you want)
},50);
}
// when while-loop breaks, resolve the promise to continue
resolve();
});
// ----------------------------------------------------------
// once it is complete, continue here
return errors
.mergeScan<any, any>(
(retryCount: any, err: any) => {
if (retryCount <= 5) {
return Observable.of(retryCount + 1);
}
},retryCountStart)
.delay(1000);
}
答案 1 :(得分:0)
据我了解,您只想在前一个流完成(即将流添加到队列)之后才开始下一个流
import { Observable, of, BehaviorSubject, from } from 'rxjs';
import { tap, finalize, filter, take, switchMap, delay } from 'rxjs/operators';
class StreamQueue {
lastStreamCompleted$: Observable<boolean> = new BehaviorSubject(true);
private runAfter<T>(lastStreamCompleted$: Observable<boolean>, stream$: Observable<T>): [Observable<boolean>, Observable<T>] {
const newLastStreamCompleted$ = new BehaviorSubject(false);
const newStream$ = lastStreamCompleted$
.pipe(
filter(lastStreamCompleted => lastStreamCompleted),
take(1),
switchMap(() => stream$),
finalize(() => newLastStreamCompleted$.next(true)),
);
return [newLastStreamCompleted$, newStream$];
}
add(stream$: Observable<any>) {
const [newLastStreamCompleted$, newStream$] = this.runAfter(this.lastStreamCompleted$, stream$);
this.lastStreamCompleted$ = newLastStreamCompleted$;
return newStream$;
}
}
const streamQueue = new StreamQueue();
streamQueue.add(from([1, 2]).pipe(delay(100))).subscribe(console.log);
setTimeout(()=>streamQueue.add(from([21, 22]).pipe(delay(100))).subscribe(console.log), 100);
streamQueue.add(from([11, 12]).pipe(delay(100))).subscribe(console.log);
// Output:
// 1
// 2
// 11
// 12
// 21
// 22