} // コンストラクタで生成するので初期化不要 public ReactiveCommand1ViewModel() { // 宣言時にインスタンスを作ってて、コンストラクタで Subscribe() Command1 .Subscribe(() => Counter1.Increment()) .AddTo(CompositeDisposable); // View の CommandParameter を加算。 WithSubscribeにより宣言からDispose登録まで一気通貫。 Command2 = new ReactiveCommand <int>() .WithSubscribe(x => Counter2.Increment(x), CompositeDisposable.Add); // CheckBox により(IObservable<bool>)から ReactiveCommand を作成 Command31 = CheckFlag31.ToReactiveCommand(initialValue: false) .WithSubscribe(() => Counter3.Increment(), CompositeDisposable.Add); var updateTimeTrigger = new Subject <Unit>(); CompositeDisposable.Add(updateTimeTrigger); // IObservable<bool> から ReactiveCommand を作成 // 実行後に一定時間は CanExecute を無効にする (ひねくれずに AsyncReactiveCommand を使えばよいと思う) Command32 = Observable.Merge( updateTimeTrigger.Select(_ => false), updateTimeTrigger.Delay(TimeSpan.FromSeconds(0.5)).Select(_ => true)) .ToReactiveCommand() .AddTo(CompositeDisposable); Command32 .Do(_ => updateTimeTrigger.OnNext(Unit.Default)) .Subscribe(_ => Counter3.Increment()) .AddTo(CompositeDisposable); }
public SettingsViewModel(IMessageBus bus, ISettingsLoader loader, ISettingsSaver saver) { SettingsCommand = new ReactiveCommand(); bus.RegisterMessageSource(SettingsCommand.Select(_ => new NavigateMainModuleMessage(ModuleNames.SettingsModule))); BackCommand = new ReactiveCommand(); bus.RegisterMessageSource(BackCommand.Select(_ => new NavigateBackMainModuleMessage())); var settings = loader.Load(); SettingsViewModels = new ISettingsSubPage[] { new GeneralSettingsViewModel(settings.General), new NetworkSettingsViewModel(settings.Network), new NotificationSettingsViewModel(settings.Notification), new AboutViewModel(), }; SelectedPage = SettingsViewModels.First(); bus.RegisterMessageSource(bus.Listen <NavigateSettingsPageMessage>().Do( msg => SelectedPage = SettingsViewModels.First(vm => vm.GetType().Name.StartsWith(msg.SettingsPage))) .Select(_ => new NavigateMainModuleMessage(ModuleNames.SettingsModule))); SaveCommand = new ReactiveCommand(); bus.RegisterMessageSource( SaveCommand.Do(_ => CommitViewModels()).Do(_ => saver.Save(settings)).Select(_ => new NavigateBackMainModuleMessage())); }
public PasteViewModel(ClipboardItem clipboardItem, IRoom room, IMessageBus bus) { if (clipboardItem.IsImage) { _imageSource = clipboardItem.LocalPath; } else { _imageSource = DependencyProperty.UnsetValue; } Caption = "Upload this " + (clipboardItem.IsImage ? "image" : "file") + "?"; LocalPath = clipboardItem.LocalPath; ShowLocalPath = !clipboardItem.IsImage; ContentType = clipboardItem.ContentType; Size = clipboardItem.Size; PasteCommand = new ReactiveCommand(); Subscribe(bus.Listen <FileUploadedMessage>().Where(msg => msg.CorrelationId == _currentCorrelation) .SubscribeUI(_ => IsFinished = true)); Subscribe(bus.Listen <FileUploadProgressChangedMessage>().Where(msg => msg.CorrelationId == _currentCorrelation) .SubscribeUI( msg => { ProgressCurrent = msg.Progress.Current; ProgressTotal = msg.Progress.Total; Debug.WriteLine("Current, total" + ProgressCurrent + ", " + ProgressTotal); })); Subscribe(bus.Listen <CorrelatedExceptionMessage>().Where(msg => msg.CorrelationId == _currentCorrelation) .SubscribeUI(msg => { IsErrored = true; IsUploading = false; LastException = msg.Exception; })); ProgressCurrent = 0; ProgressTotal = 100; Subscribe(bus.RegisterMessageSource( PasteCommand.Do(_ => { IsUploading = true; IsErrored = false; }) .Select(_ => new RequestUploadFileMessage(room.Id, clipboardItem.LocalPath, clipboardItem.ContentType)) .Do(msg => _currentCorrelation = msg.CorrelationId))); CancelCommand = new ReactiveCommand(); Subscribe(CancelCommand.Subscribe(_ => IsFinished = true)); }
public TestingViewModel() { SwitchUserCommand = new ReactiveCommand(Observable.Return(false)); LockCommand = new ReactiveCommand(); SleepCommand = new ReactiveCommand(); HibernateCommand = new ReactiveCommand(); SleepCommand.Do(_ => { Powrprof.SwitchToStandby(); }).Subscribe().AddTo(_subscriptions); HibernateCommand.Do(_ => { Powrprof.SwitchToHibernate(); }).Subscribe().AddTo(_subscriptions); LockCommand.Do(_ => { User32.LockWorkStation(); }).Subscribe().AddTo(_subscriptions); }
public PasteViewModel(ClipboardItem clipboardItem, IRoom room, IMessageBus bus) { if (clipboardItem.IsImage) { _imageSource = clipboardItem.LocalPath; } else { _imageSource = DependencyProperty.UnsetValue; } Caption = "Upload this " + (clipboardItem.IsImage ? "image" : "file") + "?"; LocalPath = clipboardItem.LocalPath; ShowLocalPath = !clipboardItem.IsImage; ContentType = clipboardItem.ContentType; Size = clipboardItem.Size; PasteCommand = new ReactiveCommand(); Subscribe(bus.Listen<FileUploadedMessage>().Where(msg => msg.CorrelationId == _currentCorrelation) .SubscribeUI(_ => IsFinished = true)); Subscribe(bus.Listen<FileUploadProgressChangedMessage>().Where(msg => msg.CorrelationId == _currentCorrelation) .SubscribeUI( msg => { ProgressCurrent = msg.Progress.Current; ProgressTotal = msg.Progress.Total; Debug.WriteLine("Current, total" + ProgressCurrent + ", " + ProgressTotal); })); Subscribe(bus.Listen<CorrelatedExceptionMessage>().Where(msg => msg.CorrelationId == _currentCorrelation) .SubscribeUI(msg => { IsErrored = true; IsUploading = false; LastException = msg.Exception; })); ProgressCurrent = 0; ProgressTotal = 100; Subscribe(bus.RegisterMessageSource( PasteCommand.Do(_ => { IsUploading = true; IsErrored = false; }) .Select(_ => new RequestUploadFileMessage(room.Id, clipboardItem.LocalPath, clipboardItem.ContentType)) .Do(msg => _currentCorrelation = msg.CorrelationId))); CancelCommand = new ReactiveCommand(); Subscribe(CancelCommand.Subscribe(_ => IsFinished = true)); }
public Game(Ball ball, Paddle paddle, IReadOnlyList <Brick> bricks, uint defaultNumLives) { Ball = ball; Paddle = paddle; Bricks = bricks; _defaultNumLives = defaultNumLives > 0 ? defaultNumLives : 1; NumLives = new ReactiveProperty <uint>(_defaultNumLives); BricksRemaining = new ReactiveProperty <int>(Bricks.Count); NumBallsInPlay = new ReactiveProperty <int>(1); Ball.Active .Where(active => !_gameOver && !active) .Subscribe(_ => NumBallsInPlay.Value -= 1); Bricks .ToObservable() .SelectMany(x => x.Active) .Where(active => active == false) .Subscribe(_ => BricksRemaining.Value -= 1); GameWon = BricksRemaining .Where(count => count == 0) .Do(x => { _gameOver = true; Ball.Active.Value = false; }) .Select(_ => Unit.Default); var noBallsInPlay = NumBallsInPlay .Where(count => count == 0) .Do(_ => NumLives.Value -= 1) .Publish() .RefCount(); noBallsInPlay .Where(_ => NumLives.Value > 0) .Delay(TimeSpan.FromMilliseconds(100)) .Subscribe(_ => UseExtraLife()); GameLost = noBallsInPlay .Where(_ => NumLives.Value == 0) .Select(_ => Unit.Default); ResetGameCmd = new ReactiveCommand(); ResetGameCmd.Subscribe(_ => ResetGame()); CreateBonusBall = new ReactiveCommand <Ball>(Observable.Defer(() => Observable.Return(!_gameOver))); CreateBonusBall .Do(_ => NumBallsInPlay.Value += 1) .SelectMany(bonusBall => DetectWhenBonusBallBecomesInactive(bonusBall)) .Subscribe(_ => NumBallsInPlay.Value -= 1); }
public Order() { var mainViewModel = Locator.Current.GetService <MainViewModel>(); BeginOrder = ReactiveCommand.Create(); ApplyOrder = ReactiveCommand.Create(); BeginOrder.Subscribe(_ => { IsOrdered = true; }); ApplyOrder .Do(_ => { IsOrdered = false; mainViewModel.BasketViewModel.Orders.Add(this); }).Subscribe(); }
public MainWindowViewModel(IContextFactory contextFactory, IMonitorFactory monitorFactory) { Readers = new ReactiveCollection <string>().AddTo(_disposables); EventHistory = new ReactiveCollection <MonitorEvent>().AddTo(_disposables); RefreshReaderListCommand = new ReactiveCommand().AddTo(_disposables); ClearEventListCommand = new ReactiveCommand().AddTo(_disposables); RefreshReaderListCommand .Select(_ => GetReaderNames(contextFactory)) .Do(UpdateReaderList) .Do(readerNames => SubscribeToReaderEvents(monitorFactory, readerNames)) .Subscribe() .AddTo(_disposables); ClearEventListCommand .Do(_ => EventHistory.ClearOnScheduler()) .Subscribe() .AddTo(_disposables); }
public RoomListViewModel(Room room, IMessageBus bus) { _room = room; _bus = bus; bus.Listen <RoomPresenceMessage>().SubscribeUI(msg => IsActive = msg.IsPresentIn(_room.Id)); _bus.Listen <RoomActivatedMessage>().Where(msg => msg.RoomId == _room.Id) .Do(_ => IsJoiningRoom = false) .SubscribeUI(_ => IsCurrentRoom = true); _bus.Listen <RoomDeactivatedMessage>().Where(msg => msg.RoomId == _room.Id) .SubscribeUI(_ => IsCurrentRoom = false); _bus.Listen <RoomActivityMessage>().Where(msg => msg.RoomId == _room.Id) .SubscribeUI(msg => RoomActivityCount += msg.Count); JoinCommand = new ReactiveCommand(); JoinCommand.Do(_ => IsJoiningRoom = true).SubscribeUI(HandleJoinCommand); }
public RoomListViewModel(Room room, IMessageBus bus) { _room = room; _bus = bus; bus.Listen<RoomPresenceMessage>().SubscribeUI(msg => IsActive = msg.IsPresentIn(_room.Id)); _bus.Listen<RoomActivatedMessage>().Where(msg => msg.RoomId == _room.Id) .Do(_ => IsJoiningRoom = false) .SubscribeUI(_ => IsCurrentRoom = true); _bus.Listen<RoomDeactivatedMessage>().Where(msg => msg.RoomId == _room.Id) .SubscribeUI(_ => IsCurrentRoom = false); _bus.Listen<RoomActivityMessage>().Where(msg => msg.RoomId == _room.Id) .SubscribeUI(msg => RoomActivityCount += msg.Count); JoinCommand = new ReactiveCommand(); JoinCommand.Do(_ => IsJoiningRoom = true).SubscribeUI(HandleJoinCommand); }
public BranchesViewController( string username, string repository, IReadOnlyList <Octokit.Branch> branches = null, IApplicationService applicationService = null) : base(UITableViewStyle.Plain) { applicationService = applicationService ?? Locator.Current.GetService <IApplicationService>(); Title = "Branches"; LoadBranches = ReactiveCommand.CreateFromTask(() => { if (branches != null) { return(Task.FromResult(branches)); } return(applicationService.GitHubClient.Repository.Branch.GetAll(username, repository)); }); LoadBranches .ThrownExceptions .Do(_ => SetErrorView()) .Select(error => new UserError(LoadErrorMessage, error)) .SelectMany(Interactions.Errors.Handle) .Subscribe(); LoadBranches .Do(_ => TableView.TableFooterView = null) .Subscribe(ItemsLoaded); Appearing .Take(1) .Select(_ => Unit.Default) .Do(_ => TableView.TableFooterView = new LoadingIndicatorView()) .InvokeReactiveCommand(LoadBranches); }
public PositionedWindowViewModel(PositionedWindow rw) { Title = rw.Title; WindowHandle = rw.WindowHandle.ToString(); Position = rw.Rectangle.ToString(); ShowState = rw.Placement.showCmd.ToString(); Flags = rw.Placement.Flags.ToString(); MoveUnderMouseCommand = new ReactiveCommand(); MoveUnderMouseCommand .Do(_ => { var p = new User32.Point(); User32.GetCursorPos(ref p); User32.SetWindowPos(rw.WindowHandle, IntPtr.Zero, p.X, p.X, 0, 0, (int)(User32.SetWindowPosFlags.SHOWWINDOW | User32.SetWindowPosFlags.NOSIZE)); //User32.MoveTo(rw.WindowHandle, new WindowRectangle(p.X, p.Y, 200, 200)); }).Subscribe(); }
public SourceTreeViewController( string username, string repository, string path, string sha, ShaType shaType, IApplicationService applicationService = null, IFeaturesService featuresService = null) : base(style: UITableViewStyle.Plain) { _username = username; _repository = repository; _path = path; _sha = sha; _shaType = shaType; _addFileCommand = ReactiveCommand.Create( ShowAddSource, this.WhenAnyValue(x => x.CanAddFile, x => x.ShaType) .Select(x => x.Item1 && x.Item2 == ShaType.Branch)); applicationService = applicationService ?? Locator.Current.GetService <IApplicationService>(); featuresService = featuresService ?? Locator.Current.GetService <IFeaturesService>(); _loadContents = ReactiveCommand.CreateFromTask(async(string shaRef) => { if (ShaType == ShaType.Branch) { var repo = await applicationService.GitHubClient.Repository.Get(username, repository); CanAddFile = repo.Permissions.Push; } else { CanAddFile = false; } var encodedShaRef = System.Web.HttpUtility.UrlEncode(shaRef); if (string.IsNullOrEmpty(path)) { return(await applicationService .GitHubClient.Repository.Content .GetAllContentsByRef(username, repository, encodedShaRef)); } return(await applicationService .GitHubClient.Repository.Content .GetAllContentsByRef(username, repository, path, encodedShaRef)); }); var addFileButton = new UIBarButtonItem(UIBarButtonSystemItem.Add); NavigationItem.RightBarButtonItem = addFileButton; _loadContents .ThrownExceptions .Do(_ => SetErrorView()) .Select(HandleLoadError) .SelectMany(Interactions.Errors.Handle) .Subscribe(); OnActivation(d => { d(_titleView .GetClickedObservable() .Subscribe(_ => ShowBranchSelector())); d(_addFileCommand .CanExecute .Subscribe(x => addFileButton.Enabled = x)); d(addFileButton .GetClickedObservable() .Select(_ => Unit.Default) .InvokeReactiveCommand(_addFileCommand)); }); Appearing .Select(_ => _sha) .Where(x => !string.IsNullOrEmpty(x)) .DistinctUntilChanged() .Do(_ => SetLoading(true)) .InvokeReactiveCommand(_loadContents); _loadContents .Do(_ => SetLoading(false)) .Subscribe(SetElements); NavigationItem.TitleView = _titleView; }
public SettingsVM( ISettingsService Settings, ICleanupData Cleanup, IConnectivityService Connectivity ) { this.Cleanup = Cleanup; this.Settings = Settings; this.Connectivity = Connectivity; this.WhenAny(x => x.Model, x => x.Value) .Where(x => x != null) .Select(m => m.UseGPS) .Subscribe(x => UseGPS = x); Reset = new ReactiveAsyncCommand(Connectivity.WifiAvailable()); Reset.RegisterAsyncTask(OnReset); var setting_changed = this.WhenAny(x => x.UseGPS, x => x.Model, (gps, model) => (model.Value != null) ? model.Value.UseGPS != gps.Value : false); Save = new ReactiveCommand(setting_changed); Messenger.RegisterMessageSource( Save .Do(_ => saveModel()) .Select(_ => Page.Previous) ); RefreshVocabulary = new ReactiveCommand(Connectivity.WifiAvailable()); RefreshVocabulary .Subscribe(_ => { Messenger.SendMessage(Page.SetupVocabulary); }); ManageTaxa = new ReactiveCommand(); Messenger.RegisterMessageSource( ManageTaxa .Select(_ => Page.TaxonManagement) ); UploadData = new ReactiveCommand(); Messenger.RegisterMessageSource( UploadData .Select(_ => Page.Upload) ); DownloadData = new ReactiveCommand(); Messenger.RegisterMessageSource( DownloadData .Select(_ => Page.Download) ); Info = new ReactiveCommand(); Messenger.RegisterMessageSource( Info .Select(_ => Page.Info) ); ImportExport = new ReactiveCommand(); Messenger.RegisterMessageSource( ImportExport .Select(_ => Page.ImportExport) ); Settings .SettingsObservable() .Subscribe(x => Model = x); }
public MapManagementVM( IConnectivityService Network, IMapTransferService MapService, IMapStorageService MapStorage, INotificationService Notifications, [Dispatcher] IScheduler Dispatcher ) { Contract.Requires(Network != null); Contract.Requires(MapService != null); Contract.Requires(MapStorage != null); Contract.Requires(Notifications != null); this.Network = Network; this.MapService = MapService; this.MapStorage = MapStorage; this.FirstActivation() .Subscribe(_ => getMaps.Execute(null)); MapList = getMaps.RegisterAsyncFunction(_ => MapStorage.getAllMaps().Select(m => new MapVM(m))) .SelectMany(vms => vms.ToList()) .ObserveOn(Dispatcher) .CreateCollection(); MapList.ItemsAdded .Subscribe(item => _local_map_register.Add(item.ServerKey, Unit.Default)); MapList.ItemsRemoved .Subscribe(item => _local_map_register.Remove(item.ServerKey)); SelectMap = new ReactiveCommand<MapVM>(vm => !vm.IsDownloading); SelectMap .Select(vm => vm as IElementVM<Map>) .ToMessage(Messenger, MessageContracts.VIEW); SelectMap .Select(_ => Page.Previous) .ToMessage(Messenger); DeleteMap = new ReactiveCommand<MapVM>(vm => !vm.IsDownloading); DeleteMap .Do(vm => MapList.Remove(vm)) .Select(vm => vm.Model) .Where(map => map != null) .Subscribe(map => MapStorage.deleteMap(map)); _IsOnlineAvailable = this.ObservableToProperty( this.OnActivation() .SelectMany(Network.WifiAvailable().TakeUntil(this.OnDeactivation())) .Do(x => { }) , x => x.IsOnlineAvailable, false); SearchMaps = new ReactiveAsyncCommand(_IsOnlineAvailable); _SearchResults = this.ObservableToProperty<MapManagementVM, IReactiveCollection<MapVM>>( SearchMaps.RegisterAsyncFunction(s => searchMapsImpl(s as string)) .ObserveOn(Dispatcher) .Select(result => { try { return new ReactiveCollection<MapVM>(result.Select(x => new MapVM(null) { ServerKey = x })) as IReactiveCollection<MapVM>; } catch (Exception) { return null; } }), x => x.SearchResults); DownloadMap = new ReactiveCommand<MapVM>(vm => canBeDownloaded(vm as MapVM), Observable.Empty<Unit>()); DownloadMap .Where(downloadMap.CanExecute) .CheckConnectivity(Network, Notifications) .Do(vm => vm.IsDownloading = true) .Do(_ => CurrentPivot = Pivot.Local) .Do(vm => MapList.Add(vm)) .Subscribe(downloadMap.Execute); downloadMap.RegisterAsyncObservable(vm => { var vm_t = vm as MapVM; if (vm_t == null) return Observable.Empty<System.Tuple<MapVM, Map>>(); else return MapService.downloadMap(vm_t.ServerKey) .ShowServiceErrorNotifications(Notifications) .Catch((WebException ex) => { Notifications.showNotification(DiversityResources.MapManagement_Message_NoPermissions); return Observable.Empty<Map>(); }) .Select(map => System.Tuple.Create(vm_t, map)); }) .ObserveOn(Dispatcher) .Select(t => { if (t.Item1 != null) // VM { if (t.Item2 != null) // Map { t.Item1.SetModel(t.Item2); } else { MapList.Remove(t.Item1); } } return t.Item1; }).Subscribe(_ => SelectMap.RaiseCanExecuteChanged()); }