Why do subscriptions interact with each other?

I am experimenting with RX and am facing the following problem (at least I perceive it as a problem). The following code creates an observable and subscribes to it twice. I thought that subscriptions should act independently , so the code below prints two lines, one for each subscription, each time you press a key. But this is not the case, I always get only one subscription to process a certain key stroke, a semi-random first or second. Why is this happening and what is the β€œrecommended” way to make several observers?

static IEnumerable<ConsoleKeyInfo> KeyPresses() { for (; ; ) { var currentKey = Console.ReadKey(true); if (currentKey.Key == ConsoleKey.Enter) yield break; yield return currentKey; } } static void Main() { var timeToStop = new ManualResetEvent(false); var keypresses = KeyPresses().ToObservable(); keypresses.Subscribe(key => Console.WriteLine(key.Key + "1"), () => timeToStop.Set()); keypresses.Subscribe(key => Console.WriteLine(key.Key + "2"), () => timeToStop.Set()); timeToStop.WaitOne(); } 
+4
source share
1 answer

The reason for this particular behavior was that the observed was cold . The value of each subscriber consumed a ReadKey call in .GetNext (). As soon as I "warm up" the observed, calling

 var keypresses = KeyPresses().ToObservable().Publish(); 

Each subscriber received his own value.

+2
source

Source: https://habr.com/ru/post/1299225/


All Articles