Rx framework – IObservable<T>.Repeat

Having looked at a number of extension methods in Rx which allows you to combine two observable collections in some way, namely:

There are also extension methods which allow you to repeatedly subscribe to the same observable collection, the suitably name IObservable<T>.Repeat method.

If the repeated observable collection is pre-determined, i.e. regardless of when you subscribe to the observable it’ll always return the same set of values (such as Observable.Return(1)), then those same values will be repeated in the resulting observable collection. This type of observable collections are referred to as Cold Observables, the enumeration equivalent of these will be an array whose values have been defined upfront.

Conversely, if the observable collection’s values are determined at the point of subscription, then when the observable collection is repeated it might yield a different set of values (e.g. when you use the Observable.Defer method to generate an observable collection). This type of observable collections are referred to as Hot Observables, the enumeration equivalent of these will be an Iterator which uses yield return to return whatever value it has at the point of execution.

You can call Repeat either as an extension method:

var zs = xs.Repeat(3);

or as a static 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 argument, it’ll repeatedly subscribe to the same observable collection indefinitely

2. When you supply the Repeat method with a repeat count, the count actually means how many times in total the observable collection will be subscribed. I.e. xs.Repeat(1) subscribes to xs once, and xs.Repeat(0) will not subscribe to xs at all.

3. If an exception is thrown during any repetition of the observable collection, the resulting observable collection excepts too as illustrated below:

image


Yan Cui

I’m an AWS Serverless Hero and the author of Production-Ready Serverless. I have run production workload at scale in AWS for nearly 10 years and I have been an architect or principal engineer with a variety of industries ranging from banking, e-commerce, sports streaming to mobile gaming. I currently work as an independent consultant focused on AWS and serverless.

You can contact me via Email, Twitter and LinkedIn.

Hire me.