NbonD
NbonD

Reputation: 327

RxJS - reusing an observable which has completed

Link to code in stackblitz

Is there a way to repeat a completed observable multiple times?

Say I have a button that on click creates an interval observable that emits 10 values, then completes:

fromEvent(button, 'click').pipe(
    switchMapTo(interval(500)),
    takeWhile(i => i < 10)
)

In the subscription I want to handle both the next and the complete methods:

.subscribe(
    i => console.log(i),
    () => {},
    () => console.log('completed')
);

In this way - the first click will emit one sequence and once it completes, subsequent clicks will not emit again. Is there any way to write this so that all clicks emit the sequence?

Upvotes: 0

Views: 1232

Answers (1)

Hitmands
Hitmands

Reputation: 14159

I think you should complete the inner observable and not the whole sequence. (takeWhile should be piped to interval);

You should use switchMap only if you are happy to dismiss the old sequence once a new click event comes in. mergeMap or concatMap otherwise.

const sequence = () => interval(500).pipe(take(10));

fromEvent(button, 'click').pipe(
    switchMap(sequence),
)

Upvotes: 1

Related Questions