问题描述
我正在尝试使用 retry
和 delay
函数,我希望函数会在 1000 毫秒延迟后调用,但它没有,这里有什么错误?看控制台输出,是同一时间16:22:48.
I am trying to use retry
with delay
function, I expect function will call after 1000ms delay, but it doesnot, what can be error here?look at console output, it is same time 16:22:48.
我预计 16:22:48、16:22:59 ...
I expect there 16:22:48, 16:22:59 ...
canCreate: boolean;
getSomeFunction(): Observable<boolean> {
return new Observable<boolean>(
observer => {
const canCreate = null; // this is just null for now, will some value later
if (canCreate == null) {
observer.error('error');
} else {
observer.next(true);
}
observer.complete();
}
)
}
this.getSomeFunction()
.do((value) => {
this.cCreate = value;
}, (error) => {
console.log(error + new Date().toTimeString());
})
.delay(1000)
.retry(10)
.subscribe(
value => this.cCreate = value,
error => {
this.cCreate = false;
},
() => {}
);
}
和控制台结果是:
推荐答案
delay()
用于在 observable 发出的事件之间引入延迟.但是 observable 永远不会发出任何事件.它只是立即出错.
delay()
is used to introduce a delay between events emitted by the observable. But the observable never emits any event. It just errors immediately.
您正在寻找的是retryWhen()
,它允许决定在多长时间后重试:
What you're looking for is retryWhen()
, which allows deciding after how long to retry:
RxJS 5:
.retryWhen(errors => errors.delay(1000).take(10))
RxJS 6:
import { retryWhen, delay, take } from 'rxjs/operators'
someFunction().pipe(
// ...
retryWhen(errors => errors.pipe(delay(1000), take(10)))
)
这将在 10 次尝试后完成整个 observable.如果你想在 10 次尝试后出错整个 observable,retryWhen 回调返回的 observable 必须抛出:
This will complete the whole observable after 10 attempts. If you want to error the whole observable after 10 attempts, the observable returned by the retryWhen callback must throw:
RxJS 5:
.retryWhen(errors => errors.delay(1000).take(10).concat(Observable.throw()))
RxJS 6:
import { retryWhen, delay, take, concatMap, throwError } from 'rxjs/operators'
someFunction().pipe(
// ...
retryWhen(errors => errors.pipe(delay(1000), take(10), concatMap(throwError)))
)
这篇关于带有延迟功能的 Rxjs 重试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!