[英]Rxjs observable wait until some condition is met
I have the following retry logic to retry an operation. 我有以下重试逻辑来重试操作。 It works fine for single request.
它适用于单个请求。 For multiple on going requests, I would like to wait for existing retry logic to complete before retrying.
对于多个正在进行的请求,我想在重试之前等待现有的重试逻辑完成。
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);
}
How can I add delay until some condition is met in the above method? 如何在上述方法中满足某些条件之前添加延迟?
You can use async
/ await
for that purpose with the Promise resolve: 您可以使用
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);
}
As i understood you want to start next stream only after previous has completed (ie add stream to queue) 据我所知,你只想在上一次完成之后启动下一个流(即添加流到队列)
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.