私は RX を試していて、次の問題に出くわしました (少なくとも私はそれを問題として認識しています)。次のコードは、オブザーバブルを作成し、それを 2 回サブスクライブします。サブスクリプションは独立して動作する必要があると考えたので、以下のコードは、キーを押すたびにサブスクリプションごとに 1 行ずつ、2 行を出力します。しかし、そうではありません。特定のキー ストロークを処理するサブスクリプションは常に 1 つだけです。なぜこれが起こっているのですか?複数のオブザーバーを行うための「推奨される」方法は何ですか?
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();
}