当前位置: 首页>>代码示例>>C#>>正文


C# ReactiveCommand.RegisterAsync方法代码示例

本文整理汇总了C#中ReactiveCommand.RegisterAsync方法的典型用法代码示例。如果您正苦于以下问题:C# ReactiveCommand.RegisterAsync方法的具体用法?C# ReactiveCommand.RegisterAsync怎么用?C# ReactiveCommand.RegisterAsync使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在ReactiveCommand的用法示例。


在下文中一共展示了ReactiveCommand.RegisterAsync方法的13个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: LoginRouteViewModel

 public LoginRouteViewModel(IScreen hostScreen)
 {
     HostScreen = hostScreen;
     var authentication = new Authentication();
     var canLogin = this.WhenAny(x => x.LoginName,
         x => x.Password,
         (l, p) => !String.IsNullOrWhiteSpace(l.Value) && !String.IsNullOrWhiteSpace(p.Value));
     LoginCommand = new ReactiveCommand(canLogin);
     var loggedIn = LoginCommand.RegisterAsync(_ => Observable.Start(() =>
     {
         var authenticationResult = authentication.AuthenticateAsync(LoginName,
             Password).
                                                   Result;
         return authenticationResult == AuthenticationResult.Authenticated
             ? "Přihlášen"
             : "Nepřihlášen";
     }));
     loggedIn.Subscribe(s =>
     {
         if (s == "Přihlášen")
             HostScreen.Router.Navigate.Execute(new PersonListViewModel(HostScreen));
     });
     message = new ObservableAsPropertyHelper<string>(loggedIn,
         s => raisePropertyChanged("Message"));
 }
开发者ID:jiravanet,项目名称:Prezentace-ReactiveUI,代码行数:25,代码来源:LoginRouteViewModel.cs

示例2: PersonListViewModel

 public PersonListViewModel(IScreen hostScreen, IPersonRepository personRepository = null)
 {
     HostScreen = hostScreen;
     personRepository = personRepository ?? new PersonRepository();
     Persons = new ReactiveList<PersonItemViewModel>();
     NewPersonCommand = new ReactiveCommand(null);
     NewPersonCommand.RegisterAsyncAction(_ => { }).Subscribe(_ => HostScreen.Router.Navigate.Execute(new PersonAddViewModel(HostScreen)));
     RefreshCommand = new ReactiveCommand(null);
     var refresh = RefreshCommand.RegisterAsync<List<Person>>(_ => Observable.Start(() => personRepository.RetrievePersonsAsync().
                                                                                                           Result));
     refresh.Subscribe(list =>
     {
         using (Persons.SuppressChangeNotifications())
         {
             Persons.Clear();
             Persons.AddRange(personRepository.RetrievePersonsAsync().
                                               Result.Select(d => new PersonItemViewModel(d.FirstName,
                                                                      d.LastName,
                                                                      d.Age)));
         }
     });
     MessageBus.Current.Listen<Person>().
                Subscribe(p =>
                {
                    personRepository.AddPerson(p);
                    RefreshCommand.Execute(null);
                });
 }
开发者ID:jiravanet,项目名称:Prezentace-ReactiveUI,代码行数:28,代码来源:PersonListViewModel.cs

示例3: AllowConcurrentExecutionTest

        public void AllowConcurrentExecutionTest()
        {
            (new TestScheduler()).With(sched => {
                var fixture = new ReactiveCommand(null, true, sched);

                Assert.True(fixture.CanExecute(null));

                var result = fixture.RegisterAsync(_ => Observable.Return(4).Delay(TimeSpan.FromSeconds(5), sched))
                    .CreateCollection();
                Assert.Equal(0, result.Count);

                sched.AdvanceToMs(25);
                Assert.Equal(0, result.Count);

                fixture.Execute(null);
                Assert.True(fixture.CanExecute(null));
                Assert.Equal(0, result.Count);

                sched.AdvanceToMs(2500);
                Assert.True(fixture.CanExecute(null));
                Assert.Equal(0, result.Count);

                sched.AdvanceToMs(5500);
                Assert.True(fixture.CanExecute(null));
                Assert.Equal(1, result.Count);
            });
        }
开发者ID:niefan,项目名称:ReactiveUI,代码行数:27,代码来源:ReactiveCommandTest.cs

示例4: CanExecuteShouldChangeOnInflightOp

        public void CanExecuteShouldChangeOnInflightOp()
        {
            (new TestScheduler()).With(sched => {
                var canExecute = sched.CreateHotObservable(
                    sched.OnNextAt(0, true),
                    sched.OnNextAt(250, false),
                    sched.OnNextAt(500, true),
                    sched.OnNextAt(750, false),
                    sched.OnNextAt(1000, true),
                    sched.OnNextAt(1100, false)
                    );

                var fixture = new ReactiveCommand(canExecute);
                int calculatedResult = -1;
                bool latestCanExecute = false;

                fixture.RegisterAsync(x =>
                    Observable.Return((int)x*5).Delay(TimeSpan.FromMilliseconds(900), RxApp.MainThreadScheduler))
                    .Subscribe(x => calculatedResult = x);

                fixture.CanExecuteObservable.Subscribe(x => latestCanExecute = x);

                // CanExecute should be true, both input observable is true
                // and we don't have anything inflight
                sched.AdvanceToMs(10);
                Assert.True(fixture.CanExecute(1));
                Assert.True(latestCanExecute);

                // Invoke a command 10ms in
                fixture.Execute(1);

                // At 300ms, input is false
                sched.AdvanceToMs(300);
                Assert.False(fixture.CanExecute(1));
                Assert.False(latestCanExecute);

                // At 600ms, input is true, but the command is still running
                sched.AdvanceToMs(600);
                Assert.False(fixture.CanExecute(1));
                Assert.False(latestCanExecute);

                // After we've completed, we should still be false, since from
                // 750ms-1000ms the input observable is false
                sched.AdvanceToMs(900);
                Assert.False(fixture.CanExecute(1));
                Assert.False(latestCanExecute);
                Assert.Equal(-1, calculatedResult);

                sched.AdvanceToMs(1010);
                Assert.True(fixture.CanExecute(1));
                Assert.True(latestCanExecute);
                Assert.Equal(calculatedResult, 5);

                sched.AdvanceToMs(1200);
                Assert.False(fixture.CanExecute(1));
                Assert.False(latestCanExecute);
            });
        }
开发者ID:niefan,项目名称:ReactiveUI,代码行数:58,代码来源:ReactiveCommandTest.cs

示例5: PersonAddViewModel

 public PersonAddViewModel(IScreen hostScreen)
 {
     HostScreen = hostScreen;
     var canAdd = this.WhenAny(x => x.FirstName,
         x => x.LastName,
         x => x.Age,
         (f, l, a) => !String.IsNullOrWhiteSpace(f.Value) && !String.IsNullOrWhiteSpace(l.Value) && a.Value > 17 && a.Value < 120);
     AddCommand = new ReactiveCommand(canAdd);
     var add = AddCommand.RegisterAsync(_ => Observable.Start(() => MessageBus.Current.SendMessage(new Person(FirstName,
                                                                                  LastName,
                                                                                  Age))));
     add.Subscribe(_ => HostScreen.Router.NavigateBack.Execute(null));
 }
开发者ID:jiravanet,项目名称:Prezentace-ReactiveUI,代码行数:13,代码来源:PersonAddViewModel.cs

示例6: StreamingDataViewModel

        public StreamingDataViewModel(DataFeed dataFeed)
        {
            AllValues = new ReactiveList<int>();
            AllValuesViewModels = AllValues.CreateDerivedCollection(x => x);

            StartRecievingData = new ReactiveCommand();

            var s = StartRecievingData.RegisterAsync(x => dataFeed.GetInfiniteSequence(1000))
                .Subscribe(d =>
                {
                    TheValue = d; //this works how I expect
                    //AllValues.Add(d); //this crashes. Why?
                });
        }
开发者ID:pdoh00,项目名称:ReactiveSandbox,代码行数:14,代码来源:StreamingDataViewModel.cs

示例7: WebCallViewModel

        /// <summary>
        /// Setup the lookup logic, and use the interface to do the web call.
        /// </summary>
        /// <param name="caller"></param>
        public WebCallViewModel(IWebCaller caller)
        {
            // Do a search when nothing new has been entered for 800 ms and it isn't
            // an empty string... and don't search for the same thing twice.

            var newSearchNeeded = this.WhenAny(p => p.InputText, x => x.Value)
                .Throttle(TimeSpan.FromMilliseconds(800), RxApp.TaskpoolScheduler)
                .DistinctUntilChanged()
                .Where(x => !string.IsNullOrWhiteSpace(x));

            _doWebCall = new ReactiveCommand();
            newSearchNeeded.InvokeCommand(_doWebCall);

            // Run the web call and save the results back to the UI when done.
            var webResults = _doWebCall.RegisterAsync(x => caller.GetResult(x as string));

            // The results are stuffed into the property, on the proper thread
            // (ToProperty takes care of that) when done. We never want the property to
            // be null, so we give it an initial value of "".
            webResults
                .ToProperty(this, x => x.ResultText, out _ResultTextOAPH, "");
        }
开发者ID:nikqw,项目名称:ReactiveUI.Samples,代码行数:26,代码来源:WebCallViewModel.cs

示例8: NotificationsListViewModel

        public NotificationsListViewModel(INotificationsClient notificationsApi)
        {
            Notifications = new ReactiveList<NotificationTileViewModel>();
            LoadNotifications = new ReactiveCommand();

            var loadedNotifications = LoadNotifications.RegisterAsync(_ =>
                //BlobCache.LocalMachine.GetAndFetchLatest("notifications", () => Observable.Return(new List<Notification>())));
                BlobCache.LocalMachine.GetAndFetchLatest("notifications", () =>
                    notificationsApi.GetAllForCurrent()));

            loadedNotifications.Subscribe(newItems => {
                using (Notifications.SuppressChangeNotifications()) {
                    var toAdd = newItems
                        .Where(x => x.Repository.Owner.Id != 9919 && x.Repository.Owner.Id != 1089146)
                        .Select(x => new NotificationTileViewModel(x))
                        .ToArray();

                    Notifications.Clear();
                    Notifications.AddRange(toAdd);
                    //Notifications.AddRange(new[] { new NotificationTileViewModel(null) });
                }
            });
        }
开发者ID:paulcbetts,项目名称:starter-sample,代码行数:23,代码来源:NotificationsListViewModel.cs

示例9: RegisterAsyncFunctionSmokeTest

        public void RegisterAsyncFunctionSmokeTest()
        {
            (new TestScheduler()).With(sched => {
                var fixture = new ReactiveCommand();
                IReactiveDerivedList<int> results;

                results = fixture.RegisterAsync(_ =>
                    Observable.Return(5).Delay(TimeSpan.FromSeconds(5), sched)).CreateCollection();

                var inflightResults = fixture.IsExecuting.CreateCollection();
                sched.AdvanceToMs(10);
                Assert.True(fixture.CanExecute(null));

                fixture.Execute(null);
                sched.AdvanceToMs(1005);
                Assert.False(fixture.CanExecute(null));

                sched.AdvanceToMs(5100);
                Assert.True(fixture.CanExecute(null));

                new[] {false, true, false}.AssertAreEqual(inflightResults);
                new[] {5}.AssertAreEqual(results);
            });
        }
开发者ID:niefan,项目名称:ReactiveUI,代码行数:24,代码来源:ReactiveCommandTest.cs

示例10: RAOShouldActuallyRunOnTheTaskpool

        public void RAOShouldActuallyRunOnTheTaskpool()
        {
            var deferred = RxApp.MainThreadScheduler;
            var taskpool = RxApp.TaskpoolScheduler;

            try {
                var testDeferred = new CountingTestScheduler(Scheduler.Immediate);
                var testTaskpool = new CountingTestScheduler(Scheduler.NewThread);
                RxApp.MainThreadScheduler = testDeferred;
                RxApp.TaskpoolScheduler = testTaskpool;

                var fixture = new ReactiveCommand();
                var result = fixture.RegisterAsync(x =>
                    Observable.Return((int)x*5).Delay(TimeSpan.FromSeconds(1), RxApp.TaskpoolScheduler));

                fixture.Execute(1);
                Assert.Equal(5, result.First());

                Assert.True(testDeferred.ScheduledItems.Count >= 1);
                Assert.True(testTaskpool.ScheduledItems.Count >= 1);
            } finally {
                RxApp.MainThreadScheduler = deferred;
                RxApp.TaskpoolScheduler = taskpool;
            }
        }
开发者ID:niefan,项目名称:ReactiveUI,代码行数:25,代码来源:ReactiveCommandTest.cs

示例11: MultipleSubscribersShouldntDecrementRefcountBelowZero

        public void MultipleSubscribersShouldntDecrementRefcountBelowZero()
        {
            (new TestScheduler()).With(sched => {
                var fixture = new ReactiveCommand();
                var results = new List<int>();
                bool[] subscribers = new[] {false, false, false, false, false};

                var output = fixture.RegisterAsync(_ =>
                    Observable.Return(5).Delay(TimeSpan.FromMilliseconds(5000), sched));
                output.Subscribe(x => results.Add(x));

                Enumerable.Range(0, 5).Run(x => output.Subscribe(_ => subscribers[x] = true));

                Assert.True(fixture.CanExecute(null));

                fixture.Execute(null);
                sched.AdvanceToMs(2000);
                Assert.False(fixture.CanExecute(null));

                sched.AdvanceToMs(6000);
                Assert.True(fixture.CanExecute(null));

                Assert.True(results.Count == 1);
                Assert.True(results[0] == 5);
                Assert.True(subscribers.All(x => x));
            });
        }
开发者ID:niefan,项目名称:ReactiveUI,代码行数:27,代码来源:ReactiveCommandTest.cs

示例12: MultipleResultsFromObservableShouldntDecrementRefcountBelowZero

        public void MultipleResultsFromObservableShouldntDecrementRefcountBelowZero()
        {
            (new TestScheduler()).With(sched => {
                bool latestExecuting = false;
                var fixture = new ReactiveCommand(null, false, sched);

                var results = fixture
                    .RegisterAsync(_ => new[] {1, 2, 3}.ToObservable())
                    .CreateCollection();
                fixture.IsExecuting.Subscribe(x => latestExecuting = x);

                fixture.Execute(1);
                sched.Start();

                Assert.Equal(3, results.Count);
                Assert.Equal(false, latestExecuting);
            });
        }
开发者ID:niefan,项目名称:ReactiveUI,代码行数:18,代码来源:ReactiveCommandTest.cs

示例13: CommitHintViewModel

        public CommitHintViewModel(string filePath, IVisualStudioOps vsOps, UserSettings settings = null, IGitRepoOps gitRepoOps = null, IFilesystemWatchCache watchCache = null)
        {
            FilePath = filePath;
            watchCache = watchCache ?? _defaultWatchCache;
            _gitRepoOps = gitRepoOps ?? new GitRepoOps();
            UserSettings = settings ?? new UserSettings();

            IsGitHubForWindowsInstalled = _gitRepoOps.IsGitHubForWindowsInstalled();

            this.Log().Info("Starting Commit Hint for {0}", filePath);

            this.WhenAny(x => x.FilePath, x => x.Value)
                .Where(x => !String.IsNullOrWhiteSpace(x))
                .Select(_gitRepoOps.FindGitRepo)
                .ToProperty(this, x => x.RepoPath, out _RepoPath);

            this.WhenAny(x => x.RepoPath, x => x.Value)
                .Where(x => !String.IsNullOrWhiteSpace(x))
                .Select(_gitRepoOps.ProtocolUrlForRepoPath)
                .ToProperty(this, x => x.ProtocolUrl, out _ProtocolUrl);

            Open = new ReactiveCommand(this.WhenAny(x => x.ProtocolUrl, x => !String.IsNullOrWhiteSpace(x.Value)));
            GoAway = new ReactiveCommand();
            RefreshStatus = new ReactiveCommand(this.WhenAny(x => x.RepoPath, x => !String.IsNullOrWhiteSpace(x.Value)));
            RefreshLastCommitTime = new ReactiveCommand(this.WhenAny(x => x.RepoPath, x => !String.IsNullOrWhiteSpace(x.Value)));
            ShowTFSGitWarning = new ReactiveCommand();
            HelpMe = new ReactiveCommand();

            var repoWatchSub = this.WhenAny(x => x.RepoPath, x => x.Value)
                .Where(x => !String.IsNullOrWhiteSpace(x))
                .Select(x => watchCache.Register(Path.Combine(x, ".git", "refs")).Select(_ => x))
                .Switch()
                .InvokeCommand(RefreshLastCommitTime);

            RefreshLastCommitTime.RegisterAsync(_ => _gitRepoOps.LastCommitTime(RepoPath))
                .StartWith(_gitRepoOps.ApplicationStartTime)
                .ToProperty(this, x => x.LastRepoCommitTime, out _LastRepoCommitTime);

            MessageBus.Current.Listen<Unit>("AnyDocumentChanged")
                .Timestamp(RxApp.MainThreadScheduler)
                .Select(x => x.Timestamp)
                .StartWith(_gitRepoOps.ApplicationStartTime)
                .ToProperty(this, x => x.LastTextActiveTime, out _LastTextActiveTime);

            var refreshDisp = this.WhenAny(x => x.LastTextActiveTime, x => Unit.Default)
                .Buffer(TimeSpan.FromSeconds(5), RxApp.TaskpoolScheduler)
                .Where(x => x.Count > 0)
                .StartWith(new List<Unit> { Unit.Default })
                .ObserveOn(RxApp.MainThreadScheduler)
                .InvokeCommand(RefreshStatus);

            this.WhenAny(x => x.LastRepoCommitTime, x => x.LastTextActiveTime, x => x.MinutesTimeOverride, (commit, active, _) => active.Value - commit.Value)
                .Select(x => x.Ticks < 0 ? TimeSpan.Zero : x)
                .Select(x => MinutesTimeOverride != null ? TimeSpan.FromMinutes(MinutesTimeOverride.Value) : x)
                .Select(x => LastCommitTimeToOpacity(x))
                .ToProperty(this, x => x.SuggestedOpacity, out _SuggestedOpacity, 1.0);

            var hintState = new Subject<CommitHintState>();
            hintState.ToProperty(this, x => x.HintState, out _HintState);

            Open.Subscribe(_ => vsOps.SaveAll());

            RefreshStatus.RegisterAsync(_ => _gitRepoOps.GetStatus(RepoPath))
                .ToProperty(this, x => x.LatestRepoStatus, out _LatestRepoStatus);

            this.WhenAny(x => x.SuggestedOpacity, x => x.LatestRepoStatus, (opacity, status) => new { Opacity = opacity.Value, Status = status.Value })
                .Select(x => {
                    if (x.Status == null) return CommitHintState.Green;
                    if (!x.Status.Added.Any() &&
                        !x.Status.Removed.Any() &&
                        !x.Status.Modified.Any() &&
                        !x.Status.Missing.Any()) return CommitHintState.Green;

                    if (x.Opacity >= 0.95) return CommitHintState.Red;
                    if (x.Opacity >= 0.6) return CommitHintState.Yellow;
                    return CommitHintState.Green;
                })
                .Subscribe(hintState);

            // NB: Because _LastRepoCommitTime at the end of the day creates a
            // FileSystemWatcher, we have to dispose it or else we'll get FSW
            // messages for evar.
            _inner = new CompositeDisposable(repoWatchSub, _LastRepoCommitTime, _LastTextActiveTime);
        }
开发者ID:hmemcpy,项目名称:SaveAllTheTime,代码行数:84,代码来源:CommitHintViewModel.cs


注:本文中的ReactiveCommand.RegisterAsync方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。