baozi
baozi

Reputation: 709

How to use Observable.Generate to output in a console

Why does the following code produce no output?

It's a console app to generate some random values (I am learning Reactive Extensions).

using System.Reactive.Linq;

static void Main(string[] args)
{   
    var rand = new Random();
    Observable.Generate(
        5.0,
        i => i > 0,
        i => i + rand.NextDouble() - 0.5,
        i => i,
        i => TimeSpan.FromSeconds(0.1)
    ).Subscribe(Console.WriteLine);  
}

Upvotes: 1

Views: 656

Answers (1)

Blorgbeard
Blorgbeard

Reputation: 103467

An Observable represents an asynchronous data stream. Because you are passing a time-span to Generate, the number generation is happening in a background thread.

When your Main function exits, the main thread exits. When the main thread exits, background threads are killed.

Since your Main function will exit before 0.1 seconds has elapsed, your generator doesn't have time to generate anything. Try adding Console.ReadLine(); to the end of your Main function, so the background thread isn't killed until you press a key.

Upvotes: 5

Related Questions