public void AmbMultiTest()
        {
            var now = Scheduler.ThreadPool.Now;
            var xs  = Observable.Return(10).Delay(TimeSpan.FromSeconds(5)).Concat(Observable.Range(1, 3));
            var ys  = Observable.Return(30).Delay(TimeSpan.FromSeconds(1)).Concat(Observable.Range(5, 3));
            var zs  = Observable.Return(50).Delay(TimeSpan.FromSeconds(3)).Concat(Observable.Range(9, 3));

            // win center
            var result = Observable.Amb(xs, ys, zs).ToArray().Wait();

            result[0].Is(30);
            result[1].Is(5);
            result[2].Is(6);
            result[3].Is(7);

            // win first
            result = Observable.Amb(new[] { ys, xs, zs }.AsEnumerable()).ToArray().Wait();

            result[0].Is(30);
            result[1].Is(5);
            result[2].Is(6);
            result[3].Is(7);

            // win last
            result = Observable.Amb(new[] { zs, xs, ys }.AsEnumerable()).ToArray().Wait();

            result[0].Is(30);
            result[1].Is(5);
            result[2].Is(6);
            result[3].Is(7);
        }
        public LoginControlViewModel(
            IRepositoryHosts hosts,
            ILoginToGitHubViewModel loginToGitHubViewModel,
            ILoginToGitHubForEnterpriseViewModel loginToGitHubEnterpriseViewModel)
        {
            Title           = Resources.LoginTitle;
            RepositoryHosts = hosts;
            GitHubLogin     = loginToGitHubViewModel;
            EnterpriseLogin = loginToGitHubEnterpriseViewModel;

            isLoginInProgress = this.WhenAny(
                x => x.GitHubLogin.IsLoggingIn,
                x => x.EnterpriseLogin.IsLoggingIn,
                (x, y) => x.Value || y.Value
                ).ToProperty(this, vm => vm.IsLoginInProgress);

            loginMode = this.WhenAny(
                x => x.RepositoryHosts.GitHubHost.IsLoggedIn,
                x => x.RepositoryHosts.EnterpriseHost.IsLoggedIn,
                (x, y) =>
            {
                var canLogInToGitHub     = x.Value == false;
                var canLogInToEnterprise = y.Value == false;

                return(canLogInToGitHub && canLogInToEnterprise ? LoginMode.DotComOrEnterprise
                        : canLogInToGitHub?LoginMode.DotComOnly
                       : canLogInToEnterprise ? LoginMode.EnterpriseOnly
                        : LoginMode.None);
            }).ToProperty(this, x => x.LoginMode);

            AuthenticationResults = Observable.Amb(
                loginToGitHubViewModel.Login,
                EnterpriseLogin.Login);
            CancelCommand = ReactiveCommand.Create();
        }
        public CSharpDiagnosticWorker(OmniSharpWorkspace workspace, DiagnosticEventForwarder forwarder, ILoggerFactory loggerFactory, OmniSharpOptions options)
        {
            _workspace = workspace;
            _forwarder = forwarder;
            _logger    = loggerFactory.CreateLogger <CSharpDiagnosticWorker>();
            _options   = options;

            var openDocumentsSubject = new Subject <string>();

            _openDocuments = openDocumentsSubject;

            _workspace.WorkspaceChanged += OnWorkspaceChanged;
            _workspace.DocumentOpened   += OnDocumentOpened;
            _workspace.DocumentClosed   += OnDocumentOpened;

            _disposable = openDocumentsSubject
                          .Buffer(() => Observable.Amb(
                                      openDocumentsSubject.Skip(99).Select(z => Unit.Default),
                                      Observable.Timer(TimeSpan.FromMilliseconds(100)).Select(z => Unit.Default)
                                      ))
                          .SubscribeOn(TaskPoolScheduler.Default)
                          .Select(ProcessQueue)
                          .Merge()
                          .Subscribe();
        }
예제 #4
0
파일: Listening.cs 프로젝트: ibebbs/Cmqtt
 public IObservable <ITransition> Enter()
 {
     return(Observable.Amb(
                ListenToMessagesAndTransitionToUnsubscribingWhenUserExits(),
                TransitionToUnsubscribingWhenClientDisconnects()
                ));
 }
예제 #5
0
        public void Activation()
        {
            _debugManager = IoC.Get <IDebugManager2>();

            _debugManager.DebugSessionStarted += (sender, e) => { Document = runModeDocument; IsVisible = true; };

            _debugManager.DebugSessionEnded += (sender, e) =>
            {
                Dispatcher.UIThread.InvokeAsync(() =>
                {
                    IsVisible = false;

                    Clear();
                });
            };

            _debugManager.FrameChanged += (sender, e) =>
            {
                Document = document;
                Update();
            };

            var started = Observable.FromEventPattern(_debugManager, nameof(_debugManager.TargetStarted));
            var stopped = Observable.FromEventPattern(_debugManager, nameof(_debugManager.TargetStopped));

            started.SelectMany(_ => Observable.Amb(Observable.Timer(TimeSpan.FromMilliseconds(250)).Select(o => true), stopped.Take(1).Select(o => false))).Where(timeout => timeout == true).Subscribe(s =>
            {
                Document = runModeDocument;
            });
        }
예제 #6
0
        private void Start()
        {
            var kuribo = GetComponent <Kuribo>();
            var rb     = GetComponent <Rigidbody>();

            myAttacker = GetComponent <IAttacker>();

            kuribo.OnAttackObservable
            .Subscribe(t =>
            {
                Observable.EveryFixedUpdate()
                .TakeUntil(Observable.Amb(
                               Observable.Timer(TimeSpan.FromSeconds(4)).AsUnitObservable(),
                               OnSuccessfulAttackObservable))
                .Subscribe(_ =>
                {
                    moveVector3 = (t.position - transform.position).SetY(0f).normalized *attackMoveSpeed;
                    rb.velocity = moveVector3.SetY(rb.velocity.y);
                }, () =>
                {
                    kuribo.SetEnemyMoveable(false);
                    Observable.Timer(TimeSpan.FromSeconds(attackInteraval))
                    .Subscribe(_ => kuribo.SetEnemyMoveable(true));
                });
            });

            this.OnCollisionEnterAsObservable()
            .Subscribe(hit => Hit(hit.gameObject));
        }
예제 #7
0
파일: AmbTest.cs 프로젝트: akarnokd/Rx.NET
        public void Amb_Never3_Params()
        {
            var scheduler = new TestScheduler();

            var n1 = scheduler.CreateHotObservable(
                OnNext(150, 1)
                );

            var n2 = scheduler.CreateHotObservable(
                OnNext(150, 1)
                );

            var n3 = scheduler.CreateHotObservable(
                OnNext(150, 1)
                );

            var res = scheduler.Start(() =>
                                      Observable.Amb(n1, n2, n3)
                                      );

            res.Messages.AssertEqual(
                );

            n1.Subscriptions.AssertEqual(
                Subscribe(200, 1000)
                );

            n2.Subscriptions.AssertEqual(
                Subscribe(200, 1000)
                );

            n3.Subscriptions.AssertEqual(
                Subscribe(200, 1000)
                );
        }
예제 #8
0
파일: AmbTest.cs 프로젝트: akarnokd/Rx.NET
 public void Amb_ArgumentChecking()
 {
     ReactiveAssert.Throws <ArgumentNullException>(() => Observable.Amb((IObservable <int>[])null));
     ReactiveAssert.Throws <ArgumentNullException>(() => Observable.Amb((IEnumerable <IObservable <int> >)null));
     ReactiveAssert.Throws <ArgumentNullException>(() => Observable.Amb(null, DummyObservable <int> .Instance));
     ReactiveAssert.Throws <ArgumentNullException>(() => Observable.Amb(DummyObservable <int> .Instance, null));
 }
예제 #9
0
        static void Main(string[] args)
        {
            //var textsSubject = new Subject<string>();
            //IObservable<string> texts = textsSubject.AsObservable();
            //texts
            //    .Select(txt => Observable.Return(txt + "-Result")
            //        .Delay(TimeSpan.FromMilliseconds(txt == "R1" ? 10 : 0))
            //    )
            //    .Switch()
            //    .SubscribeConsole("Merging from observable");
            //textsSubject.OnNext("R1");
            //textsSubject.OnNext("R2");
            //Thread.Sleep(20);
            //textsSubject.OnNext("R3");
            //Console.ReadKey();

            var server1 = Observable.Interval(TimeSpan.FromSeconds(1))
                          .Select(i => $"server1-{i}");
            var server2 = Observable.Interval(TimeSpan.FromSeconds(1))
                          .Select(i => $"server1-{i}");

            Observable.Amb(server1, server2)
            .Take(3)
            .SubscribeConsole();
            Console.ReadKey();
        }
예제 #10
0
        public ItemViewModel(IScreen screen = null)
        {
            HostScreen = screen ?? Locator.Current.GetService <IScreen>(); // IRoutableViewModel implementation.

            Confirm = ReactiveCommand.CreateFromObservable(OnConfirm);
            Cancel  = ReactiveCommand.CreateFromObservable(OnCancel);
            Delete  = ReactiveCommand.CreateFromObservable(OnDelete);

            // completedInternally emits when either of Confirm, Cancel or Delete emits and completes.
            var completedInternally = Observable.Amb(
                Confirm.Select(_ => _),
                Cancel.Select(_ => _),
                Delete.Select(_ => _));

            completedInternally.Subscribe(_ =>
            {
                if (HostScreen.Router.NavigationStack.LastOrDefault() == this)
                {
                    HostScreen.Router.NavigateBack.Execute().Subscribe(); // Return to the calling ViewModel when completed.

                    if (NextViewModel != null)
                    {
                        HostScreen.Router.Navigate.Execute(NextViewModel).Subscribe();
                    }
                }
            });
        }
        protected override Task <T> AwaitForResult <T>(AsyncOperationCallback <T> asyncOperationCallback)
#endif
        {
#if ASYNC
            Task <T> operationTask = asyncOperationCallback.Task;

            Task <Exception> disconnectionTask = mDisconnectionTaskCompletionSource.Task;

            Task task = await Task.WhenAny(operationTask,
                                           disconnectionTask)
                        .ConfigureAwait(false);

            if (!operationTask.IsCompleted)
            {
                Exception exception = await disconnectionTask.ConfigureAwait(false);

                asyncOperationCallback.SetException(exception);
            }

            T result = await operationTask.ConfigureAwait(false);

            return(result);
#else
            IObservable <T> merged =
                Observable.Amb
                    (asyncOperationCallback.Task.ToObservable(),
                    mDisconnectionTaskCompletionSource.Task.ToObservable()
                    .SelectMany(x => Observable.Throw <T>(x)));

            Task <T> task = merged.ToTask();

            return(task);
#endif
        }
        public CSharpDiagnosticWorker(OmniSharpWorkspace workspace, DiagnosticEventForwarder forwarder, ILoggerFactory loggerFactory)
        {
            _workspace = workspace;
            _forwarder = forwarder;
            _logger    = loggerFactory.CreateLogger <CSharpDiagnosticWorker>();

            var openDocumentsSubject = new Subject <string>();

            _openDocuments = openDocumentsSubject;

            _workspace.WorkspaceChanged += OnWorkspaceChanged;
            _workspace.DocumentOpened   += OnDocumentOpened;
            _workspace.DocumentClosed   += OnDocumentOpened;

            openDocumentsSubject
            .GroupByUntil(x => true, group => Observable.Amb(
                              group.Throttle(TimeSpan.FromMilliseconds(200)),
                              group.Distinct().Skip(99))
                          )
            .Select(x => x.ToArray())
            .Merge()
            .SubscribeOn(TaskPoolScheduler.Default)
            .Select(ProcessQueue)
            .Merge()
            .Subscribe();
        }
예제 #13
0
        private IObservable <byte[]> CreateResponseTask(byte?[] pattern)
        {
            var timeoutSequence = Observable.Throw <byte[]>(new TimeoutException()).DelaySubscription(timeout);

            return(Observable.Amb(
                       udpClient.ObserveBytes().FirstAsync(x => {
                return MatchesPattern(x, pattern);
            }),
                       timeoutSequence));
        }
예제 #14
0
 private static IObservable <Unit> GetTimeOrCount(
     IObservable <int> source, TestScheduler testScheduler,
     TimeSpan timeThreshold, int countThreshold, IObservable <Unit> manualFlush)
 {
     return(Observable.Amb(
                Observable.Timer(timeThreshold, testScheduler).Select(_ => Unit.Default).Do(_ => Console.WriteLine("Blipped from Timer")),
                source.Buffer(countThreshold).Take(1).Select(_ => Unit.Default).Do(_ => Console.WriteLine("Blipped from Buffer")),
                manualFlush.Take(1).Do(_ => Console.WriteLine("Blipped from Flush")))
            .Concat(Observable.Defer(() => GetTimeOrCount(source, testScheduler, timeThreshold, countThreshold, manualFlush))));
 }
예제 #15
0
        void Start()
        {
            //Amb  并行系列操作符  舍弃 除了第一个进行发射的obs 以外的所有obs

            Observable.Amb(
                Observable.Timer(TimeSpan.FromSeconds(1)),
                Observable.Timer(TimeSpan.FromMinutes(1)),
                Observable.Timer(TimeSpan.FromHours(1)),
                Observable.Timer(TimeSpan.FromDays(1))
                ).Subscribe(_ => print("..."));
        }
예제 #16
0
        public void AmbTest()
        {
            var enumerable0 = CreateRandomEnumerable("Acho").ToObservable();
            var enumerable1 = CreateRandomEnumerable("foo").ToObservable();
            var enumerable2 = CreateRandomEnumerable("bar").ToObservable();

            var pattern = Observable.Amb(enumerable0, enumerable1, enumerable2);

            pattern.Subscribe(Console.WriteLine);
            Thread.Sleep(1000);
        }
예제 #17
0
 // Start is called before the first frame update
 void Start()
 {
     Observable.Amb(
         Observable.Timer(TimeSpan.FromSeconds(3.0f)).Select(_ => "1 sec"),
         Observable.Timer(TimeSpan.FromSeconds(2.0f)).Select(_ => "1 sec"),
         Observable.Timer(TimeSpan.FromSeconds(1.0f)).Select(_ => "1 sec"),
         Observable.Timer(TimeSpan.FromSeconds(5.0f)).Select(_ => "1 sec"),
         Observable.Timer(TimeSpan.FromSeconds(4.0f)).Select(_ => "1 sec"),
         Observable.Timer(TimeSpan.FromSeconds(6.0f)).Select(_ => "1 sec"),
         Observable.Timer(TimeSpan.FromSeconds(8.0f)).Select(_ => "1 sec")
         ).Subscribe(name => Debug.Log(name), () => Debug.Log("On Completed"));
 }
예제 #18
0
        private void Start()
        {
            Observable.Amb(
                candleList.ObserveEveryValueChanged(list => list.All(c => c.IsAlive.Value)).Where(x => !x),
                LitCandleList.ObserveAdd().Select(_ => candleList.Count == LitCandleList.Count).Where(x => x)
                ).First()
            .Subscribe(_ => _onGameOver.OnNext(Unit.Default)).AddTo(gameObject);

            LitCandleList.ObserveAdd()
            .Select(add => add.Index)
            .Subscribe(index => _onLit.OnNext(index));
        }
 private SchedulerDelegate RouteNotification(
     IRequestDescriptor <IHandlerDescriptor?> descriptors,
     Notification notification) =>
 (_, scheduler) =>
 // ITS A RACE!
 Observable.Amb(
     Observable.Timer(_options.RequestTimeout, scheduler)
     .Select(_ => Unit.Default)
     .Do(
         _ => _logger.LogTrace("Notification was cancelled due to timeout")
         ),
     Observable.FromAsync(
예제 #20
0
        public override async Task Start()
        {
            await base.Start();

            // Calculate paths
            if (!Directory.Exists(_tempDirectory))
            {
                Directory.CreateDirectory(_tempDirectory);
            }

            // Generate an entirely unique file name
            string fileName = Invocation.Id.ToString("N") + "_" + Guid.NewGuid().ToString("N") + ".json";

            _tempFile = Path.Combine(_tempDirectory, fileName);
            if (File.Exists(_tempFile))
            {
                File.Delete(_tempFile);
            }

            // Locate the log blob
            _targetBlob = LogContainer.GetBlockBlobReference("invocations/" + _blobName);

            // Fetch the current logs if this is a continuation, we'll append to them during the invocation
            if (Invocation.IsContinuation && await _targetBlob.ExistsAsync())
            {
                await _targetBlob.DownloadToFileAsync(_tempFile, FileMode.Create);
            }

            // Capture the events into a JSON file and a plain text file
            var formatter = new JsonEventTextFormatter(EventTextFormatting.Indented, dateTimeFormat: "O");

            _eventSubscription = this.Buffer(() =>
                                             Observable.Amb(
                                                 _flushBuffer,
                                                 Observable.Timer(TimeSpan.FromSeconds(5)).Select(x => Unit.Instance))
                                             .Take(1))
                                 .Subscribe(
                onNext: evts =>
            {
                // Dump to the temp file
                using (var writer = new StreamWriter(new FileStream(_tempFile, FileMode.Append, FileAccess.Write)))
                {
                    foreach (var evt in evts)
                    {
                        formatter.WriteEvent(evt, writer);
                    }
                }

                // Upload the temp file
                UploadLog().Wait();
            });
        }
예제 #21
0
 void Start()
 {
     Observable.Amb(
         Observable.Timer(TimeSpan.FromSeconds(4.0f)).Select(_ => "4 sec"),
         Observable.Timer(TimeSpan.FromSeconds(3.0f)).Select(_ => "3 sec"),
         Observable.Timer(TimeSpan.FromSeconds(1.0f)).Select(_ => "1 sec"),
         Observable.Timer(TimeSpan.FromSeconds(7.0f)).Select(_ => "7 sec"),
         Observable.Timer(TimeSpan.FromSeconds(9.0f)).Select(_ => "9 sec")
         ).Subscribe(observableName =>
     {
         Debug.Log(observableName);
     });
 }
예제 #22
0
        public void Amb()
        {
            var source1 = Observable
                          .Timer(TimeSpan.FromSeconds(3), TimeSpan.FromSeconds(1));

            var source2 = Observable
                          .Timer(TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(1))
                          .Select(x => x * 10);

            var source = Observable.Amb(source1, source2);

            this.Subscribe(source, "Amb");
        }
예제 #23
0
        private static void Amb()
        {
            Demo.DisplayHeader("The Amb operator - picks the first observable to emit");

            var server1 = Observable.Interval(TimeSpan.FromSeconds(2)).Select(i => "Server1-" + i);
            var server2 = Observable.Interval(TimeSpan.FromSeconds(1)).Select(i => "Server2-" + i);

            Observable.Amb(server1, server2)
            .Take(3)
            .RunExample("Amb");

            //The same could have been written like:
            // server1.Amb(server2).Take(3).RunExample("Amb");
        }
예제 #24
0
        public RegisterPageViewModel(INavigationService navigationService, IUserUsecase userUsecase, IUserDialogs userDialogs) : base(navigationService)
        {
            _userUsecase = userUsecase;
            _userDialogs = userDialogs;

            Name.SetValidateAttribute(() => Name);

            RegisterCommand = new[]
            {
                Name.ObserveHasErrors,
                _busyNotifier,
            }
            .CombineLatestValuesAreAllFalse()
            .ObserveOn(SynchronizationContext.Current)
            .ToReactiveCommand()
            .WithSubscribe(() =>
            {
                _registerRequested.OnNext(Unit.Default);
                _userUsecase.Register(Name.Value);
            })
            .AddTo(_disposables);

            _registerRequested.SelectMany(_ => Observable.Using(() =>
            {
                return(new CompositeDisposable()
                {
                    _busyNotifier.ProcessStart(),
                    _userDialogs.Loading(""),
                });
            }, _ => Observable.Amb(
                                                                    _userUsecase.UserRegistered.Select <User, (User?user, Exception?error)>(user => (user, null)),
                                                                    _userUsecase.ErrorOccurred.Select <Exception, (User?user, Exception?error)>(ex => (null, ex)))
                                                                .Take(1)))
            .ObserveOn(SynchronizationContext.Current)
            .Subscribe(async t =>
            {
                if (t.user is not null)
                {
                    await _userDialogs.AlertAsync("登録が完了しました", "確認");
                    await navigationService.NavigateAsync("/MainPage");
                }
                else
                {
                    await _userDialogs.AlertAsync("登録に失敗しました", "エラー");
                }
            })
            .AddTo(_disposables);
        }
예제 #25
0
        /// <summary>
        /// race with amb for repeating until a success.
        /// </summary>
        private static void test14()
        {
            //.Timeout won't work because timeout measure between two elements the length of time.

            var timer = Observable.Timer(TimeSpan.FromSeconds(6)).Select(_ => false);
            var built = Observable.FromAsync(() => getResult())
                        //.Delay(TimeSpan.FromSeconds(0.1))
                        .Repeat()
                        .TakeWhileInclusive(succeeded => !succeeded)
                        .Where(succeeded => succeeded)
                        .Do(i => Console.WriteLine($"built pipeline reached an {i}"));

            Observable
            .Amb(built, timer)
            .Subscribe(i => Console.WriteLine($"amb ticked - {i}"),
                       (() => Console.WriteLine($"completed")));
        }
예제 #26
0
 /// <summary>
 /// 複数のObservableから一番早く値が流れてきたものを流す
 /// </summary>
 private void ExcuteAmb()
 {
     Observable
     .Amb(
         // 流れない
         Observable.Timer(TimeSpan.FromSeconds(3)).Select(_ => "3s"),
         // 流れない
         Observable.Timer(TimeSpan.FromSeconds(2)).Select(_ => "2s"),
         // 流れる
         Observable.Timer(TimeSpan.FromSeconds(1)).Select(_ => "1s"))
     .Subscribe(x => {
         Debug.Log("Amb onNext : " + x);
     }, () => {
         Debug.Log("Amb onCompleted");
     });
     // 値が流れてきたら、onCompleted
 }
예제 #27
0
        public void Activation()
        {
            _debugManager = IoC.Get <IDebugManager2>();

            IoC.Get <IStudio>().DebugPerspective.AddOrSelectTool(this);

            _debugManager.DebugSessionStarted += (sender, e) => { Enabled = false; };

            _debugManager.TargetReady += (sender, e) =>
            {
                if (_debugManager.ExtendedSession != null)
                {
                    IsVisible = true;

                    var regs = _debugManager.ExtendedSession.GetRegisters();

                    Dispatcher.UIThread.InvokeAsync(() =>
                    {
                        SetRegisters(regs);
                    });
                }
            };

            _debugManager.DebugSessionEnded += (sender, e) =>
            {
                IsVisible = false;
                Clear();
            };

            _debugManager.FrameChanged += (sender, e) =>
            {
                Enabled = true;

                if (_debugManager.ExtendedSession != null)
                {
                    var changes = _debugManager.ExtendedSession.GetRegisterChanges();

                    UpdateRegisters(changes);
                }
            };

            var started = Observable.FromEventPattern(_debugManager, nameof(_debugManager.TargetStarted));
            var stopped = Observable.FromEventPattern(_debugManager, nameof(_debugManager.TargetStopped));

            started.SelectMany(_ => Observable.Amb(Observable.Timer(TimeSpan.FromMilliseconds(250)).Select(o => true), stopped.Take(1).Select(o => false))).Where(timeout => timeout == true).Subscribe(s => Enabled = false);
        }
예제 #28
0
 private static IObservable <byte[]> CreateRmqListener(Settings settings)
 {
     return(Observable.Using(
                () => new ConnectionSession(
                    new Uri(settings.ConnectionString),
                    settings.Exchanger,
                    settings.RoutingKey),
                s => Observable.Amb(
                    Observable.FromEventPattern <BasicDeliverEventArgs>(
                        x => s.Consumer.Received += x,
                        x => s.Consumer.Received -= x)
                    .Select(x => x.EventArgs.Body),
                    Observable.Defer(() =>
     {
         s.BindQueueToExchangerAndStartConsume();
         return Observable.Return(0);
     }).SelectMany(_ => Observable.Never <byte[]>()))));
 }
예제 #29
0
        public void all_sources_are_unsubscribed_when_complete_is_received()
        {
            var sourceA = new EventOwner();
            var sourceC = new EventOwner();

            var obs = Observable.Amb(
                sourceA.GetObservableEvent(),
                Observable.Empty <IEvent <EventArgs> >(),
                sourceC.GetObservableEvent()
                );

            var stats = new StatsObserver <IEvent <EventArgs> >();

            obs.Subscribe(stats);

            Assert.IsFalse(sourceA.HasSubscriptions);
            Assert.IsFalse(sourceC.HasSubscriptions);
        }
예제 #30
0
        public async void AwaitExample3()
        {
            var enter = Observable
                        .FromEventPattern <KeyEventArgs>(this, nameof(this.KeyDown))
                        .Select(e => e.EventArgs.Key)
                        .Where(k => k == Key.Enter)
                        .FirstAsync();

            var esc = Observable
                      .FromEventPattern <KeyEventArgs>(this, nameof(this.KeyDown))
                      .Select(e => e.EventArgs.Key)
                      .Where(k => k == Key.Escape)
                      .FirstAsync();

            var dialogResult = await Observable.Amb(enter, esc);

            Console.WriteLine($"The user pressed the {dialogResult} key");
        }