Watching the asynchronous sequence with "yield return",
The following example works fine:
static IEnumerable<int> GenerateNum(int sequenceLength) { for(int i = 0; i < sequenceLength; i++) { yield return i; } } static void Main(string[] args) { //var observ = Observable.Start(() => GenerateNum(1000)); var observ = GenerateNum(1000).ToObservable(); observ.Subscribe( (x) => Console.WriteLine("test:" + x), (Exception ex) => Console.WriteLine("Error received from source: {0}.", ex.Message), () => Console.WriteLine("End of sequence.") ); Console.ReadKey(); } However, I really want to use a commented line - that is, I want to run the "number generator" asynchronously, and every time it gives a new value, I want it to be displayed on the console. It doesn't seem to work - how can I change this code to work?
When performing asynchronous execution in a console application, you can use the ToObservable(IEnumerable<TSource>, IScheduler) (see the Observable.ToObservable (IEnumerable, IScheduler) method ). For example, to use thread pool schedule, try
var observ = GenerateNum(1000).ToObservable(Scheduler.ThreadPool); This works for me ... To expand, the following complete example works exactly the way I think you intend:
static Random r = new Random(); static void Main(string[] args) { var observ = GenerateNum(1000).ToObservable(Scheduler.ThreadPool ); observ.Subscribe( (x) => Console.WriteLine("test:" + x), (Exception ex) => Console.WriteLine("Error received from source: {0}.", ex.Message), () => Console.WriteLine("End of sequence.") ); while (Console.ReadKey(true).Key != ConsoleKey.Escape) { Console.WriteLine("You pressed a key."); } } static IEnumerable<int> GenerateNum(int sequenceLength) { for (int i = 0; i < sequenceLength; i++) { Thread.Sleep(r.Next(1, 200)); yield return i; } }