Repeat the Execution of an Observable with RxJS repeat

André Staltz
InstructorAndré Staltz
Share this video with your friends

Social Share Links

Send Tweet

Operator repeat() is somewhat similar to retry(), but is not for handling operators. In this lesson we learn how repeat works.

🚨 Since we are importing interval from RxJS, we don't need to preface our Observables with Rx.Observable. You can no longer .{operator}, you need to .pipe({operator}) instead. To link together multiple Observables and Operators, the method is a bit different. You call zip first, then list your Observables, your functions, then pipe your Operators.

[00:00] Retry is a useful operator to repeat the execution of the input observable multiple times, but it only does that if there was an error happen on the input observable. Sometimes it will be useful to create repetition even if there is no error. So let's say that foo would not have the number two, then bar when mapped, would not have an error. Thus the use case for an operator called repeat.

[00:26] The usage of repeat is quite similar to the usage of retry. You can think of it as actually replace the completion notification. This complete with the whole input observable bar itself. If we do that, then it looks like this. Every time we replace that completion it would just keep on going forever because by default repeat will just repeat forever, and it will just keep on doing that. Just like retry it takes an argument here which you can specify the total amount of times that bar will be repeated.

[01:03] So we can say three, that means that after the third time that bar is executed it will just complete. If you run this we see A, B, C, D, and then after the third time it will complete. Repeat can be useful for creating observables from others, for instance that are meant to have some repeated pattern or rhythm.