开发者

Why subscriptions interact with each other?

开发者 https://www.devze.com 2022-12-17 03:48 出处:网络
I am experimenting with RX, and run across the following problem (at least I perceive it as a problem). The following code creates an observable, and subscribes to it twice. I thought subscriptions sh

I am experimenting with RX, and run across the following problem (at least I perceive it as a problem). The following code creates an observable, and subscribes to it twice. I thought subscriptions should act independently, so the code below would output two lines, one for each subscription, on each key press. But this is not the case, I always get only one subscription to handle a particular key stroke, se开发者_运维问答mi-randomly first or second. Why this is happening and what is the "recommended" way to do multiple 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();
    }


The reason for this particular behavior was that the observable was cold. Meaning each subscriber was consuming the ReadKey call on .GetNext(). As soon as I "warmed up" the observable by calling

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

each subscriber received its own value.

0

精彩评论

暂无评论...
验证码 换一张
取 消