1

I'm trying to figure out how can I use Reactive Extensions and for that I've written this simple example:

namespace ReactiveTest
{
    class Program
    {
        static void Main(string[] args)
        {
            var o = Observable.Generate(0, i => i < 10, x => AddAndWait(x), i => i * i);
            Console.WriteLine("Before");
            o.Subscribe(x => Console.WriteLine(x));
            Console.WriteLine("After");
            Console.ReadLine();
        }

        static int AddAndWait(int i)
        {
            Thread.Sleep(1000);
            return i + 1;
        }
    }
}

After watching this video I would expect to see After printed right after Before but I get squares of numbers instead, and only after that has completed I get the After message.

I understand that I'm blocking the thread but isn't that the point of this reactive stuff, to be able to surpass that limitations and continue in your main thread?

Panagiotis Kanavos
  • 120,703
  • 13
  • 188
  • 236
Sturm
  • 3,968
  • 10
  • 48
  • 78
  • The point of Reactive Extensions is to react to and process live streams of events. In this case you are *producing* anc *consuming* events on the same thread. *By default* Reactive Extensions doesn't use a new thread for either job. You can use `SubscribeOn` to specify that processing will run on a separate thread, or `ObserveOn` to specify that generation will occur on a different thread. – Panagiotis Kanavos Feb 22 '17 at 10:45
  • Possible duplicate of [Rx produce and consume on different threads](http://stackoverflow.com/questions/27247968/rx-produce-and-consume-on-different-threads) – Panagiotis Kanavos Feb 22 '17 at 10:46
  • The duplicate question and the related [ObserveOn and SubscribeOn - where the work is being done](http://stackoverflow.com/questions/20451939/observeon-and-subscribeon-where-the-work-is-being-done/) explain how this works already. The answers also explain why Reactive isn't concurrent by default – Panagiotis Kanavos Feb 22 '17 at 10:47
  • Do you know if the video I've linked is outdated by this date? There are several methods such us GenerateWithTime that I don't see anymore. – Sturm Feb 22 '17 at 10:53
  • A 2010 video is outdated by default. I don't think there even was a stable release of Rx back then. Nothing changed in respect to asynchrony and concurrency though. In this case you were trying to generate and consume the events on the same blocked thread. You *could* do it too, if you didn't use `Thread.Sleep` and the equally blocking `ReadLine`. For example, if you used `await Task.Delay(..);` in a Winforms application you'd get different results – Panagiotis Kanavos Feb 22 '17 at 11:00
  • Possible duplicate of [ObserveOn and SubscribeOn - where the work is being done](http://stackoverflow.com/questions/20451939/observeon-and-subscribeon-where-the-work-is-being-done) – Massimiliano Kraus Mar 08 '17 at 16:55

0 Answers0