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


C# ReactiveCommand.RegisterAsyncAction方法代码示例

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


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

示例1: 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

示例2: MeetingListViewModel

        public MeetingListViewModel(IAgentConnection connection,
                                    INavigationService navigation,
                                    IMeetingViewModelFactory meetingFactory)
        {
            // Enable the command once a meeting has been selected
            var enter = new ReactiveCommand(this.WhenAnyValue(v => v.SelectedMeeting, sm => sm != null));
            
            // Call the navigate method passing in the selected meeting
            _enterMeetingSub = enter
                .RegisterAsyncAction(_ => navigation.Navigate(Screen.AgentMeeting, SelectedMeeting))
                .Subscribe();
            EnterMeetingCommand = enter;

            _meetingStatusSub = connection.MeetingStatus.ObserveOn(RxApp.MainThreadScheduler).Subscribe(UpdateStatuses);

            // When we get a new list of meetings, add them to our list while suppressing changes
            _meetingUpdateSub = connection.Meetings
                .ObserveOn(RxApp.MainThreadScheduler)
                .Subscribe(meetings =>
                            {
                                using (_meetings.SuppressChangeNotifications())
                                {
                                    var toAdd = meetings
                                        .Select(meetingFactory.Create)
                                        .ToArray();

                                    _meetings.Clear();
                                    _meetings.AddRange(toAdd);
                                }
                            });

            Title = "Upcoming Appointments";
        }
开发者ID:reactiveui-forks,项目名称:VirtualSales,代码行数:33,代码来源:MeetingListViewModel.cs

示例3: VideoConfViewModel

        public VideoConfViewModel()
        {
            var playCommand = new ReactiveCommand(this.WhenAnyValue(vm => vm.IsPlaying,
                                                                    vm => vm.Config,
                                                                    (playing, config) => !playing && (config != null)));
            this.PlayCommand = playCommand;
            playCommand.RegisterAsyncAction(_ => OnPlay());

            var pauseCommand = new ReactiveCommand(this.WhenAnyValue(vm => vm.IsPlaying,
                                                                     (playing) => playing));
            pauseCommand.RegisterAsyncAction(_ => OnPause());
            this.PauseCommand = pauseCommand;
        }
开发者ID:reactiveui-forks,项目名称:VirtualSales,代码行数:13,代码来源:VideoConfViewModel.cs

示例4: MainViewModel

        public MainViewModel()
        {
            DisplayCommand = new ReactiveCommand(this.WhenAny(x => x.Name, x => !string.IsNullOrEmpty(x.Value)));
            DisplayCommand.Subscribe(_ => MessageBox.Show("You clicked on DisplayCommand: Name is " + Name));

            StartAsyncCommand = new ReactiveCommand();
            StartAsyncCommand.RegisterAsyncAction(_ =>
            {
                Progress = 0;
                while (Progress <= 100)
                {
                    Progress += 10;
                    Thread.Sleep(100);
                }
            });

        }
开发者ID:Eugene-Murray,项目名称:ReactiveUI.Samples,代码行数:17,代码来源:MainVIewModel.cs

示例5: ReflexCommandClosure

        public IReactiveCommand this[string name]
        {
            get
            {
                IReactiveCommand result;

                if (!commands.TryGetValue(name, out result))
                {
                    var closure = new ReflexCommandClosure(parent, name);
                    if (async)
                    {
                        var resultasync = new ReactiveCommand();
                        resultasync.RegisterAsyncAction(p => closure.Invoke(p));
                        result = resultasync;
                    }
                    else
                    {
                        result = new ReactiveCommand();
                        result.Subscribe(p => closure.Invoke(p));
                    }
                    commands.Add(name, result);
                }

                return result;
            }
            set
            {
                if (value != null)
                {
                    var closure = new ReflexCommandClosure(parent, name);
                    if (async)
                    {
                        value.RegisterAsyncAction(p => closure.Invoke(p));
                    }
                    else
                    {
                        value.Subscribe(p => closure.Invoke(p));
                    }
                    commands[name] = value;
                }
            }
        }
开发者ID:WorldMaker,项目名称:ReflexUX,代码行数:42,代码来源:ReflexCommandBinder.cs

示例6: AgentMeetingViewModel

        public AgentMeetingViewModel(
            IAgentConnection agentConnection, 
            ISharedDataService sharedDataService,
            INavigationService navigation,
            IViewModelLocator locator,
            IPlatformServices platformServices)
        {
            _sharedDataService = sharedDataService;
            _agentConnection = agentConnection;
            NavigationPane = locator.NavigationPaneViewModel;

            var startcmd = new ReactiveCommand(this.WhenAnyValue(vm => vm.MeetingStarted, vm => vm.Meeting.VideoConf.VideoInitCompleted, vm => vm.Meeting, (started, video, mtg) => !started && mtg != null));
            _startMeetingSub = startcmd.RegisterAsyncTask(async _ =>
                                                                {
                                    MeetingStarted = true;
                                    Meeting.VideoConf.Config = await _agentConnection.StartMeeting(Meeting.Id);
                                }).Subscribe();

            var endcmd = new ReactiveCommand(this.WhenAnyValue(vm => vm.MeetingStarted, vm => vm.Meeting.VideoConf.VideoInitCompleted, (meetingStarted, videoStarted) => meetingStarted && videoStarted));
            _endMeetingSub = endcmd.RegisterAsyncAction(_ => navigation.BackCommand.Execute(null)).Subscribe();

            StartMeetingCommand = startcmd;
            EndMeetingCommand = endcmd;

            _agentConnection.ClientInMeeting.ToProperty(this, t => t.IsClientInMeeting, out _isClientInMeeting);

            
            var savePdfCmd = new ReactiveCommand(this.WhenAnyValue(vm => vm.MeetingStarted, vm => vm.Meeting.VideoConf.VideoInitCompleted, (meetingStarted, videoStarted) => meetingStarted && videoStarted));
            _pdfSub = savePdfCmd.RegisterAsyncTask(async _ =>
                                                         {
                                                            await _agentConnection.GenerateIllustration(Meeting.Id, _sharedDataService.Person);
                                               }).Subscribe();

            _pdfAvailableSub = _agentConnection.PdfAvailable.ObserveOn(RxApp.MainThreadScheduler).Subscribe(async p =>
                                                    {
                                                        var result = await _agentConnection.GetIllustrationPdfAsync(p);
                                                        await platformServices.SaveAndLaunchFile(new System.IO.MemoryStream(result), "pdf");
                                                    });

            SavePdfCommand = savePdfCmd;


            _titleSub = this.WhenAnyValue(
                vm => vm.Meeting.Client,
                (client) =>
                string.Format("Meeting with {0}",
                              client.FullName)
                )
                            .ObserveOn(RxApp.MainThreadScheduler)
                            .Subscribe(t => Title = t);

            MeetingStatus = GetMeetingStatusString(IsClientInMeeting, MeetingStarted);
            _meetingStatusSub = this.WhenAnyValue(
                         vm => vm.MeetingStarted,
                         vm => vm.IsClientInMeeting,
                         (started, clientIn) => GetMeetingStatusString(clientIn, started))
                         .ObserveOn(RxApp.MainThreadScheduler)
                         .Subscribe(t => MeetingStatus = t);

            //_titleSub = this.WhenAnyValue(
            //             vm => vm.Meeting.Client,
            //             vm => vm.MeetingStarted,
            //             vm => vm.IsClientInMeeting,
            //             (client, started, clientIn) =>
            //                 string.Format("Meeting with {0}. Started: {1} Client Joined: {2}",
            //                    client.FullName, started, clientIn)
            //             )
            //             .ObserveOn(RxApp.MainThreadScheduler)
            //             .Subscribe(t => Title = t);


            // When the meeting's active tool changes, set the Tool and page number
            // into the shared state so it'll be propagated.

            // Get an observable for the currently set tool
            var activeToolObs = this.WhenAnyValue(vm => vm.Meeting.ActiveTool)
                .Where(t => t != null);

            // Every time the tool changes, watch the new tool's CurrentPageNumber
            // for changes.
            //
            // When we get a change, convert that into a ToolIdAndPageNumber, bringing in
            // the owning tool id.
            var pageChangedObs = activeToolObs
                 .Select(t => t.WhenAnyValue(v => v.CurrentPageNumber, 
                                    p => new ToolIdAndPageNumber { ToolId = t.ToolId, PageNumber = p})
                        )
                 .Switch() // Only listen to the most recent sequence of property changes (active tool)
                 .Log(this, "Current Page Changed", t => string.Format("Tool: {0}, Page: {1}", t.ToolId, t.PageNumber));
         
            // Every time the tool changes, select the tool id and current page number
            var toolChangedObs = activeToolObs
                .Select(t => new ToolIdAndPageNumber { ToolId = t.ToolId, PageNumber = t.CurrentPageNumber })
                .Log(this, "Tool Changed", t => string.Format("Tool: {0}, Page: {1}", t.ToolId, t.PageNumber));

            
            // Merge them together - tool changes and current page of the tool
            _meetingStateSub = toolChangedObs
                .Merge(pageChangedObs)
                .Subscribe(t => sharedDataService.MeetingState.State = t);
//.........这里部分代码省略.........
开发者ID:reactiveui-forks,项目名称:VirtualSales,代码行数:101,代码来源:AgentMeetingViewModel.cs

示例7: NavigationService

        public NavigationService(ISettings settings,
                                 IViewModelLocator locator)
        {
            _settings = settings;
            _locator = locator;

            _viewModelLocator.Add(Screen.Login, () => locator.LoginViewModel);
            _viewModelLocator.Add(Screen.AgentMeeting, () => locator.AgentMeetingViewModel);
            _viewModelLocator.Add(Screen.MeetingList, () => locator.MeetingListViewModel);
            _viewModelLocator.Add(Screen.ClientMeeting, () => locator.ClientMeetingViewModel);
            _viewModelLocator.Add(Screen.Lobby, () => locator.LobbyViewModel);


            // Setup the backstack

            var stackChanged = Observable.FromEventPattern<NotifyCollectionChangedEventHandler, NotifyCollectionChangedEventArgs>(
                h => _navigationStack.CollectionChanged += h,
                h => _navigationStack.CollectionChanged -= h).Select(p => p.EventArgs);

            var count = stackChanged.Select(_ => _navigationStack.Count);

            var backCmd = new ReactiveCommand(count.Select(v => v > 1));
            _backCmdSub = backCmd.RegisterAsyncAction(_ => _navigationStack.Pop(), Scheduler.Immediate).Subscribe();
            BackCommand = backCmd;

            var latestAfterPop = stackChanged
                .Where(args => args.Action == NotifyCollectionChangedAction.Remove)
                .Select(a => new
                {
                    Popped = (Tuple<Screen, IScreenViewModel>)a.OldItems[0],
                    Latest = _navigationStack.Peek()
                });


            _poppedSub = latestAfterPop
                .ObserveOn(RxApp.MainThreadScheduler)
                .Subscribe(t =>
                           {
                               // Navigate away from the prev one
                               t.Popped.Item2.OnNavigatedAway();

                               // Nav to the prev one
                               t.Latest.Item2.OnNavigatedTo(NavigateDirection.Back);

                               CurrentViewModel = t.Latest.Item2;
                               Screen = t.Latest.Item1;

                               // Cleanup
                               t.Popped.Item2.Dispose();
                           });


            var added = stackChanged
               .Where(args => args.Action == NotifyCollectionChangedAction.Add)
               .Select(a =>
                       {
                           var t = (Tuple<Screen, IScreenViewModel>)a.NewItems[0];
                           return Tuple.Create(t.Item1, t.Item2, NavigateDirection.Forward);
                       });


            var removed = latestAfterPop.Select(t => Tuple.Create(t.Latest.Item1, t.Latest.Item2, NavigateDirection.Back));



            var connectable = added.Merge(removed).Publish();
            _currentScreenSub = connectable.Connect(); // make it hot

            CurrentScreen = connectable;
        }
开发者ID:reactiveui-forks,项目名称:VirtualSales,代码行数:70,代码来源:NavigationService.cs

示例8: ToolViewModel

        protected ToolViewModel(Guid toolId)
        {
            Pages = _pages;
            ToolId = toolId;

            // Listen for the page count changing
            var currentWithCount = _pages.CountChanged
                .CombineLatest(_currentPageIndex, (count, current) => 
                    new {Count = count, Current = current})
                .Publish(); // We have multiple listenser, so publish the value (multicast)

            // Enable the next page command when the count is less than the total number of pages
            var nextPageCmd = new ReactiveCommand(currentWithCount.Select(t => 
                                                        t.Current + 1 < t.Count &&
                                                        t.Count > 1));
           
            // When the command is invoked, call GoToPage with the next page num.
            _nextPageSub = nextPageCmd
                .RegisterAsyncAction(_ =>
                    GoToPage(_currentPageIndex.Value + 1), // _currentPageIndex stores the current value
                    Scheduler.Immediate)
                .Subscribe();

            // Enable the preious page if current is greater than 0 and there's at least two pages
            var prevPageCmd = new ReactiveCommand(currentWithCount.Select(t => 
                                                        t.Current > 0 && 
                                                        t.Count > 1));
            // When the command is invoked, call GoToPage with the previous index
            _prevPageSub = prevPageCmd
                .RegisterAsyncAction(_ =>
                    GoToPage(_currentPageIndex.Value - 1), // _currentPageIndex stores the current value
                    Scheduler.Immediate)
                .Subscribe();

            NextPageCommand = nextPageCmd;
            PreviousPageCommand = prevPageCmd;

            // When the current index changes, get the current tool and expose it as a property
            // As pages flow through, 
            _currentPageIndex
                .Select(i => i >= 0 ? _pages[i] : (IToolPage)null)
                .DistinctUntilChanged()
                .Scan((prev, current) =>
                      {
                          if (prev != null)
                              prev.OnNavigatedAway();
                          if (current != null)
                              current.OnNavigatedTo();

                          // This element will become prev on the next pass
                          return current;
                      })
                .ToProperty(this, tvm => tvm.CurrentPage, out _currentPage);

            // Expose the current page index as a property
            _currentPageIndex.ToProperty(this, tvm => tvm.CurrentPageNumber, out _currentPageNumber);

            

            // Once all of our listeners are attached, turn on the stream
            _currentSub = currentWithCount.Connect();
        }
开发者ID:reactiveui-forks,项目名称:VirtualSales,代码行数:62,代码来源:ToolViewModel.cs

示例9: ClientLobbyViewModel

        public ClientLobbyViewModel(IClientConnection clientConnection,
                                    INavigationService navigation,
                                    IMeetingViewModelFactory meetingFactory)
        {
            _clientConnection = clientConnection;
            _navigation = navigation;


            // This command should be available when we're not already waiting
            // but not before we get the Meeting data back.
            // Check for a non null meeting and make sure WaitingForAgent is false
            var cmd = new ReactiveCommand(this.WhenAnyValue(
                vm => vm.WaitingForAgent,
                vm => vm.Meeting,
                (wait, mtg) => !wait && mtg != null));

            // This is the navigation function.
            // We want to go to the ClientMeeting screen once the following conditions are met:
            // 1) We are the Active screen (IsActive == true)
            // 2) We have the meeting VM back (this gets set as a result of the previous call)
            // 3) We get the MeetingDetails (non-null). This means the agent hit Start Meeting
            //
            // Combine the three things we're observing into an anon type
            // Then check them against our conditions
            // If all true, then navigate
            _navSub = _clientConnection.MeetingDetails
                                       .CombineLatest(this.WhenAnyValue(vm => vm.IsActive),
                                                      this.WhenAnyValue(vm => vm.Meeting),
                                                      (det, act, mtg) => new { Details = det, IsActive = act, Meeting = mtg })
                .Where(t => t.IsActive && t.Details != null && t.Meeting != null)
                                       .Subscribe(c =>
                                       {
                                           if (c.Details.MeetingId == Meeting.Id)
                                           {
                                               Meeting.VideoConf.Config = c.Details;
                                               _navigation.Navigate(Screen.ClientMeeting, Meeting);
                                           }
                                       });

            // The command's action will set the WaitingForAgent to true so we can't click
            // Join again. It will then send the join message to the server
            _joinMeetingSub = cmd.RegisterAsyncAction(p =>
                                                      {
                                                          WaitingForAgent = true;
                                                          ConnectedToMeeting = true;
                                                          MeetingJoined = true;
                                                          _clientConnection.JoinMeeting(Meeting.Id);
                                                      }).Subscribe();

            JoinMeetingCommand = cmd;


            var connectCmd = new ReactiveCommand(this.WhenAnyValue(p => p.MeetingId, p => p.ConnectedToMeeting, p => p.RequestInProgress, (id, connected, requestInProgress) => !string.IsNullOrEmpty(id) && id.Length == 6 && !connected && !requestInProgress));
            connectCmd.RegisterAsyncAction(p =>
                                           {
                                               RequestInProgress = true;
                                               // Kick off the GetMeetingDetails call
                                               // Normally you can't await a task in a ctor, but
                                               // Rx solves that by turning it into an Observable.
                                               // When we get the meeting DTO back, turn it into a MeetingVM
                                               // and expose it as a property here.
                                               clientConnection.GetMeetingDetails(MeetingId)
                                                               .ToObservable()
                                                               .ObserveOn(RxApp.MainThreadScheduler)
                                                               .Select(p1 => p1 == null ? null : meetingFactory.Create(p1))
                                                               .Subscribe(p1 =>
                                                                          {
                                                                              Error = string.Empty;
                                                                              if (p1 == null)
                                                                              {
                                                                                  Error = "Meeting with id " + MeetingId + " does not exist.";
                                                                                  return; // nothing, meeting doesn't exist
                                                                              }
                                                                              Meeting = p1;
                                                                              RequestInProgress = false;
                                                                              JoinMeetingCommand.Execute(null);
                                                                          });


                                           });
            ConnectCommand = connectCmd;

            var disconnectCmd = new ReactiveCommand(this.WhenAnyValue(p => p.ConnectedToMeeting, p => p.RequestInProgress, (connected,requestInProgress) => connected && !requestInProgress));
            disconnectCmd.RegisterAsyncAction(p =>
                                              {
                                                  WaitingForAgent = false;
                                                  ConnectedToMeeting = false;
                                                  if (MeetingJoined)
                                                  {
                                                      _clientConnection.LeaveMeeting(Meeting.Id);
                                                      MeetingJoined = false;
                                                  }

                                                  _clientConnection.LeaveMeeting(Meeting.Id);
                                                  Meeting = null;
                                              });


            DisconnectCommand = disconnectCmd;

//.........这里部分代码省略.........
开发者ID:reactiveui-forks,项目名称:VirtualSales,代码行数:101,代码来源:ClientLobbyViewModel.cs


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