Reputation: 6428
As I understand Subscribe method should be asynchronous whereas Run is synchronous. But this piece of code is working in synchronous manner. Can anybody fix it?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reactive.Linq;
namespace RxExtensionsDemo
{
class Program
{
static void Main(string[] args)
{
IObservable<int> source = Observable.Generate<int, int>(0, i => i < 10000, i => i + 1, i => i * i);
IDisposable subscription = source.Subscribe(x => { Console.WriteLine("Received {0} from source", x); }, ex =>
{
Console.WriteLine("Error occured");
}, () =>
{
Console.WriteLine("Source said there are no more messages to follow");
});
Console.WriteLine("Asynchronous");
Console.ReadKey();
}
}
}
I always see Asynchronous written to console at the last.
Upvotes: 2
Views: 139
Reputation: 106816
By default Observable.Generate
uses Scheduler.CurrentThread
. However, you can specify a different scheduler to get the desired asynchronous behavior:
IObservable<int> source = Observable.Generate<int, int>(
0,
i => i < 10000,
i => i + 1,
i => i * i,
Scheduler.NewThread
);
The Scheduler
class is in the System.Reactive.Concurrency
namespace.
Other possible asynchronous predefined schedulers are Scheduler.TaskPool
and Scheduler.ThreadPool
.
Upvotes: 3