Rx framework — IObservable<T>.Repeat

Hav­ing looked at a num­ber of exten­sion meth­ods in Rx which allows you to com­bine two observ­able col­lec­tions in some way, name­ly:

There are also exten­sion meth­ods which allow you to repeat­ed­ly sub­scribe to the same observ­able col­lec­tion, the suit­ably name IObservable<T>.Repeat method.

If the repeat­ed observ­able col­lec­tion is pre-deter­mined, i.e. regard­less of when you sub­scribe to the observ­able it’ll always return the same set of val­ues (such as Observable.Return(1)), then those same val­ues will be repeat­ed in the result­ing observ­able col­lec­tion. This type of observ­able col­lec­tions are referred to as Cold Observ­ables, the enu­mer­a­tion equiv­a­lent of these will be an array whose val­ues have been defined upfront.

Con­verse­ly, if the observ­able collection’s val­ues are deter­mined at the point of sub­scrip­tion, then when the observ­able col­lec­tion is repeat­ed it might yield a dif­fer­ent set of val­ues (e.g. when you use the Observable.Defer method to gen­er­ate an observ­able col­lec­tion). This type of observ­able col­lec­tions are referred to as Hot Observ­ables, the enu­mer­a­tion equiv­a­lent of these will be an Iter­a­tor which uses yield return to return what­ev­er val­ue it has at the point of exe­cu­tion.

You can call Repeat either as an exten­sion method:

var zs = xs.Repeat(3);

or as a sta­t­ic method:

var zs = Observable.Repeat(xs, 3);

There are a few things you should keep in mind when you’re using the Repeat method though.

1. If you call Repeat method with no argu­ment, it’ll repeat­ed­ly sub­scribe to the same observ­able col­lec­tion indef­i­nite­ly

2. When you sup­ply the Repeat method with a repeat count, the count actu­al­ly means how many times in total the observ­able col­lec­tion will be sub­scribed. I.e. xs.Repeat(1) sub­scribes to xs once, and xs.Repeat(0) will not sub­scribe to xs at all.

3. If an excep­tion is thrown dur­ing any rep­e­ti­tion of the observ­able col­lec­tion, the result­ing observ­able col­lec­tion excepts too as illus­trat­ed below:

image