Observable.Defer - need some clarification as to what exactly it does

Viewed 4336

Say I want to generate an asynchronous stream of random numbers that pumps out a new value every 100 milliseconds. While trying to come up with a solution, my first attempt looked something like this:

        var random = new Random();
        Observable.Start(() => random.Next())
                  .Delay(TimeSpan.FromMilliseconds(100))
                  .Repeat()
                  .Subscribe(Console.WriteLine);

If you try and run this, you'll notice that it just keeps repeating the same value over and over again. OK, I guess I misunderstood how Repeat works. After playing around for a bit, I came up with this and it worked:

        var random = new Random();
        Observable.Defer(()=> Observable.Start(() => random.Next()))
                  .Delay(TimeSpan.FromMilliseconds(100))
                  .Repeat()
                  .Subscribe(Console.WriteLine);

So I went to the MSDN documentation to understand what Defer is actually doing, and this is what it says:

Returns an observable sequence that invokes the observable factory whenever a new observer subscribes.

I guess my confusion is this: in my code sample, I'm only ever subscribing to the Observable once, so why is it seemingly invoking the Observable.Start(...) over and over? Or am I misunderstanding Repeat()? Any clarification would be awesome.

2 Answers
Related