[英]RxJS Observable: repeat using count and then using notifier
我有一個Observable發出Either = Success | Failure
Either = Success | Failure
:
import { Observable } from 'rxjs';
type Success = { type: 'success' };
type Failure = { type: 'failure' };
type Either = Success | Failure;
const either$ = new Observable<Either>(observer => {
console.log('subscribe');
observer.next({ type: 'failure' });
observer.complete();
return () => {
console.log('unsubscribe');
};
});
我想允許用戶在Observable完成並且最后一個值為Failure
時“重試” observable。
( retry{,When}
運算符在這里無濟於事,因為它們在error
通道上處理error
。因此,我相信我們應該考慮repeat
。
我想要:
n
次,直到最后一個值不是Failure
。 repeat$
)時,請再次重復該observable。 例如:
// subscribe
// next { type: 'failure' }
// unsubscribe
// retry 2 times:
// subscribe
// next { type: 'failure' }
// unsubscribe
// subscribe
// next { type: 'failure' }
// unsubscribe
// now, wait for repeat notifications…
// on retry notification:
// subscribe
// next { type: 'failure' }
// unsubscribe
我無法提出更簡單的方法,但是代碼可以滿足您的要求。
參見https://stackblitz.com/edit/typescript-yqcejk
defer(() => {
let retries = 0;
const source = new BehaviorSubject(null);
return merge(source, repeat$.pipe(filter(() => retries <= MAX_RETRIES)))
.pipe(
concatMapTo(either$),
tap(value => {
const action = value as Either;
if (action.type === 'failure') {
if (retries < MAX_RETRIES) {
retries += 1;
source.next(null);
}
} else {
retries = 0;
}
})
)
}).subscribe(console.log);
我不得不手動計算重試次數。
該代碼有兩個事件source
,它們分別是自動重試的事件source
和repeat$
的用戶重試源。 所有的事件映射到either$
使用concatMapTo
。 作為副作用,我們要么next()
重試,要么不做任何等待用戶重試的操作。
使用filter(() => retries >= MAX_RETRIES)
抑制用戶重試,直到達到MAX_RETRIES
計數。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.