Skip to content

Commit

Permalink
refactor ksRepeat
Browse files Browse the repository at this point in the history
  • Loading branch information
KEIII committed Mar 31, 2023
1 parent 081f15b commit 8f2d3ae
Showing 1 changed file with 12 additions and 4 deletions.
16 changes: 12 additions & 4 deletions src/pipeable_operators.ts
Original file line number Diff line number Diff line change
Expand Up @@ -429,25 +429,33 @@ export const ksRepeat = <A>(count: number): PipeableOperator<A, A> => {
return source.constructor(observer => {
let soFar = 0;
const innerSub = _restartableObservable<A>();
const repeatSubj = ksSubject<void>();

const subscribeForRepeat = () => {
innerSub.restartWith(source).subscribe({
next: observer.next,
complete: () => {
if (++soFar < count) {
// repeat asynchronously
// waiting for the previous to be unsubscribed
Promise.resolve().then(subscribeForRepeat);
repeatSubj.next();
} else {
observer.complete();
}
},
});
};

const repeatSub = repeatSubj
.pipe(ksDelay(0)) // defer repeat so prev innerSub unsubscribes
.subscribe({ next: subscribeForRepeat });

subscribeForRepeat();

return innerSub;
return {
unsubscribe: () => {
repeatSub.unsubscribe();
innerSub.unsubscribe();
},
};
});
};
};
Expand Down

0 comments on commit 8f2d3ae

Please sign in to comment.