// <param name="isFinal">
        // we verify 2 words, isFinal -> we verified 1 word already
        // </param>
        public VerifyMnemonicViewModel(List <string> seedWords, string previouslyVerified)
            : base(Locator.Current.GetService <IViewStackService>())
        {
            Global    = Locator.Current.GetService <Global>();
            SeedWords = seedWords;

            while (WordToVerify == null || WordToVerify == previouslyVerified)
            {
                // "random" check words were written. no need for CSPRNG
                WordToVerify = seedWords.RandomElement();
            }

            IndexToVerify = seedWords.IndexOf(WordToVerify);

            VerifiedCommand = ReactiveCommand.CreateFromObservable(() =>
            {
                if (previouslyVerified != null)
                {
                    Global.UiConfig.IsBackedUp = true;
                    Global.UiConfig.ToFile();                     // successfully backed up!
                    ViewStackService.PopPage(false);              // this
                    ViewStackService.PopPage(false);              // previouslyVerified
                    ViewStackService.PopPage(false);
                    ViewStackService.PopPage();                   // words
                }
                else
                {
                    ViewStackService.PushPage(new VerifyMnemonicViewModel(seedWords, WordToVerify)).Subscribe();
                }
                return(Observable.Return(Unit.Default));
            });

            FailedCommand = ReactiveCommand.CreateFromObservable(() =>
            {
                ViewStackService.PopPage(false);                  // this
                if (previouslyVerified != null)
                {
                    ViewStackService.PopPage(false);                  // previouslyVerified
                }
                return(Observable.Return(Unit.Default));
            });
        }
        private static void InitializeCommands(CsvImporterViewModel <T> csvImporterViewModel)
        {
            csvImporterViewModel.ParseFileCommand = ReactiveCommand.CreateFromObservable(() =>
                                                                                         Observable.Start(() => csvImporterViewModel.Parser.ParseFile(csvImporterViewModel.FilePath)),
                                                                                         csvImporterViewModel.WhenAnyValue(x => x.FilePath)
                                                                                         .Select(path => !string.IsNullOrWhiteSpace(path) && File.Exists(path)));
            csvImporterViewModel.ParseFileCommand
            .Where(r => r != null)
            .ObserveOn(RxApp.MainThreadScheduler)
            .Subscribe(r =>
            {
                csvImporterViewModel.Parsed   = r.Parsed;
                csvImporterViewModel.Warnings = r.Warnings;
            });

            csvImporterViewModel.PickFileCommand = ReactiveCommand.CreateFromObservable(() =>
                                                                                        csvImporterViewModel.PickFileInteraction.Handle(Unit.Default));
            csvImporterViewModel.PickFileCommand
            .Subscribe(path => csvImporterViewModel.FilePath = path);
        }
Example #3
0
        public CoffeeListViewModel(IPopupViewStackService parameterViewStackService, ICoffeeService coffeeService)
        {
            _viewStackService = parameterViewStackService;
            _coffeeService    = coffeeService;

            CoffeeDetails = ReactiveCommand.CreateFromObservable <CoffeeCellViewModel, Unit>(ExecuteNavigate);

            Refresh = ReactiveCommand.CreateFromTask(ExecuteRefresh);

            _coffeeService
            .ChangeSet
            .Transform(x => new CoffeeCellViewModel(x.Id, x.Name, x.Species, x.Regions, x.Image))
            .Sort(SortExpressionComparer <CoffeeCellViewModel> .Ascending(p => p.Name))
            .Bind(out _coffeeList)
            .DisposeMany()
            .Subscribe()
            .DisposeWith(Garbage);

            CoffeeDetails = ReactiveCommand.CreateFromObservable <CoffeeCellViewModel, Unit>(ExecuteNavigate).DisposeWith(Garbage);
        }
Example #4
0
        public MainViewModel(AppBootstrapper appBootstrapper, IViewStackService viewStackService = null, IFirebaseAuthService firebaseAuthService = null)
        {
            viewStackService    = viewStackService ?? Locator.Current.GetService <IViewStackService>();
            firebaseAuthService = firebaseAuthService ?? Locator.Current.GetService <IFirebaseAuthService>();

            MenuItems = GetMenuItems();

            NavigateToMenuItem = ReactiveCommand.CreateFromObservable <IPageViewModel, Unit>(
                pageVm => viewStackService.PushPage(pageVm, resetStack: true));

            this.WhenAnyValue(x => x.Selected)
            .Where(x => x != null)
            .StartWith(MenuItems.First())
            .Select(x => Locator.Current.GetService <IPageViewModel>(x.TargetType.FullName))
            .InvokeCommand(NavigateToMenuItem);

            SignOut = ReactiveCommand.Create(() => firebaseAuthService.SignOut());

            SignOut.Subscribe(_ => appBootstrapper.MainView = new SignInViewModel(appBootstrapper));
        }
        public TaskListViewModel(
            IScreen hostScreen,
            ILogger <TaskListViewModel> logger,
            SourceList <TaskViewModel> taskSourceList,
            OperationQueue taskQueue)
        {
            HostScreen      = hostScreen;
            _logger         = logger;
            _taskSourceList = taskSourceList;
            _taskQueue      = taskQueue;

            _taskSourceList.Connect()
            .ObserveOnDispatcher()
            .Bind(out TaskList)
            .DisposeMany()
            .Subscribe();

            StopTaskCommand      = ReactiveCommand.CreateFromObservable <object?, Unit>(StopTask);
            ClearAllTasksCommand = ReactiveCommand.CreateFromTask(ClearAllTasksAsync);
        }
        public void IsExecutingTicksAsExecutionsProgress() =>
        new TestScheduler().With(
            scheduler =>
        {
            IObservable <Unit> execute           = Observables.Unit.Delay(TimeSpan.FromSeconds(1), scheduler);
            ReactiveCommand <Unit, Unit> fixture = ReactiveCommand.CreateFromObservable(() => execute, outputScheduler: scheduler);
            fixture.IsExecuting.ToObservableChangeSet(ImmediateScheduler.Instance).Bind(out ReadOnlyObservableCollection <bool> isExecuting).Subscribe();

            fixture.Execute().Subscribe();
            scheduler.AdvanceByMs(100);

            Assert.Equal(2, isExecuting.Count);
            Assert.False(isExecuting[0]);
            Assert.True(isExecuting[1]);

            scheduler.AdvanceByMs(901);

            Assert.Equal(3, isExecuting.Count);
            Assert.False(isExecuting[2]);
        });
Example #7
0
 public InputViewModel()
 {
     _hub = MessageHub.Instance;
     //ExecuteCommand = ReactiveCommand.Create(OnExecute);
     ExecuteCommand = ReactiveCommand.Create(OnExecute,
                                             this.WhenAny(
                                                 x => x.Code,
                                                 hasCode => !string.IsNullOrWhiteSpace(hasCode.Value)));
     //.Subscribe(_ => OnExecute());
     //OkButton = ReactiveCommand.Create(
     //    this.WhenAny(x => x.Code, y => y.Query,
     //        (x, y) => !string.IsNullOrWhiteSpace(x.Value) && !string.IsNullOrWhiteSpace(y.Value)) );
     // this.WhenAny(x => x.Code, y=> y.Query, (x, y) => !string.IsNullOrWhiteSpace(x) && !string.IsNullOrWhiteSpace(y));
     LoadCommand = ReactiveCommand.CreateFromObservable(OnLoad);
     LoadCommand.Subscribe(ReadFile);
     SaveCommand = ReactiveCommand.Create(OnSave,
                                          this.WhenAny(
                                              x => x.FileName,
                                              fileName => !string.IsNullOrWhiteSpace(fileName.Value)));
 }
Example #8
0
        public void IsExecutingRemainsTrueAsLongAsExecutionPipelineHasNotCompleted()
        {
            var execute = new Subject <Unit>();
            var fixture = ReactiveCommand.CreateFromObservable(() => execute);

            fixture
            .Execute()
            .Subscribe();

            Assert.True(fixture.IsExecuting.FirstAsync().Wait());

            execute.OnNext(Unit.Default);
            Assert.True(fixture.IsExecuting.FirstAsync().Wait());

            execute.OnNext(Unit.Default);
            Assert.True(fixture.IsExecuting.FirstAsync().Wait());

            execute.OnCompleted();
            Assert.False(fixture.IsExecuting.FirstAsync().Wait());
        }
Example #9
0
 private void ConfigureLoadCacheCommand()
 {
     LoadCacheCommand = ReactiveCommand.CreateFromObservable(_cacheService.GetPullRequests);
     LoadCacheCommand.IsExecuting.ToPropertyEx(this, x => x.Loading);
     LoadCacheCommand.ThrownExceptions.Subscribe(ex =>
     {
         //TODO Handle cache exceptions
     });
     LoadCacheCommand.Subscribe(x =>
     {
         if (x.Any())
         {
             _pullRequestData.AddRange(x);
         }
         else
         {
             Observable.Return(Unit.Default).InvokeCommand(AddCommand);
         }
     });
 }
        private static IDisposable BindRemoveAction(
            this ProxyPopupContext context,
            IProxyManager proxyManager)
        {
            context.RemoveProxyCommand = ReactiveCommand.CreateFromObservable(
                (ProxyModel proxyModel) => context.RemoveProxy(proxyManager, proxyModel),
                null,
                RxApp.MainThreadScheduler);

            return(context.RemoveProxyCommand
                   .Accept(proxyModel =>
            {
                if (proxyModel == context.SelectedProxy)
                {
                    context.SelectedProxy = context.Proxies.FirstOrDefault();
                }

                context.Proxies.Remove(proxyModel);
            }));
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="T:ReactiveUIAroundMe.Portable.ViewModels.HomePageViewModel"/> class.
        /// </summary>
        /// <param name="signalRClient">Signal RC lient.</param>
        /// <param name="scheduler">Scheduler.</param>
        /// <param name="applicationStateHandler">Application state handler.</param>
        /// <param name="storage">Storage.</param>
        /// <param name="webServiceController">Web service controller.</param>
        /// <param name="log">Log.</param>
        /// <param name="device">Device.</param>
        public HomePageViewModel(IScheduler scheduler, ApplicationStateHandler applicationStateHandler,
                                 ISQLiteStorage storage, WebServiceController webServiceController, GoogleMapsWebServiceController googleMapsWebServiceController,
                                 IPathLocator pathLocator, ILogger log, IDevice device, IScreen hostScreen, ILocationManager locationManager)
            : base(storage, scheduler, log, applicationStateHandler, webServiceController, googleMapsWebServiceController, pathLocator, hostScreen,
                   locationManager)
        {
            Title = "Welcome";

            _webServiceController = webServiceController;
            _device = device;

            scheduler.ScheduleAsync((arg1, arg2) => SetupSQLite());
            scheduler.ScheduleAsync((arg1, arg2) => Load());

            var canSearch = this.WhenAnyValue(
                vm => vm.CurrentLocation,
                (location) => location.Timestamp != default(DateTimeOffset));

            SearchCommand = ReactiveCommand.CreateFromObservable(SearchAsync, canSearch, scheduler);
        }
        public void ExecuteTicksErrorsInAnyChildCommandThroughThrownExceptions()
        {
            var child1        = ReactiveCommand.CreateFromObservable(() => Observables.Unit);
            var child2        = ReactiveCommand.CreateFromObservable(() => Observable.Throw <Unit>(new InvalidOperationException("oops")));
            var childCommands = new[] { child1, child2 };
            var fixture       = ReactiveCommand.CreateCombined(childCommands);

            fixture
            .ThrownExceptions
            .ToObservableChangeSet(ImmediateScheduler.Instance).Bind(out var thrownExceptions).Subscribe();

            fixture
            .Execute()
            .Subscribe(
                _ => { },
                _ => { });

            Assert.Equal(1, thrownExceptions.Count);
            Assert.Equal("oops", thrownExceptions[0].Message);
        }
Example #13
0
        /* COOLSTUFF: Why the Screen here?
         *
         * Every RoutableViewModel has a pointer to its IScreen. This is really
         * useful in a unit test runner, because you can create a dummy screen,
         * invoke Commands / change Properties, then test to see if you navigated
         * to the correct new screen
         */
        public WelcomeViewModel(IScreen screen)
        {
            HostScreen = screen;

            /* COOLSTUFF: Where's the Execute handler?
             *
             * We want this command to display a MessageBox. However,
             * displaying a MessageBox is a very View'y thing to do. Instead,
             * the ViewModel is going to create the ReactiveCommand and the
             * *View* is going to Subscribe to it. That way, we can test in
             * the Unit Test runner that HelloWorld is Execute'd at the right
             * times, but still display the MessageBox when the code runs
             * normally,
             */

            HelloWorld       = ReactiveCommand.CreateFromObservable(() => MessageInteractions.ShowMessage.Handle("It works!!!"));
            NavigateToSecond = ReactiveCommand.CreateFromTask(async() => await HostScreen.Router.Navigate.Execute(new SecondViewModel(HostScreen)).Select(_ => Unit.Default));

            this.WhenNavigatedTo(() => Bar());
        }
        public void ExecuteCanBeCancelled() =>
        new TestScheduler().With(
            scheduler =>
        {
            IObservable <Unit> execute           = Observables.Unit.Delay(TimeSpan.FromSeconds(1), scheduler);
            ReactiveCommand <Unit, Unit> fixture = ReactiveCommand.CreateFromObservable(() => execute, outputScheduler: scheduler);
            fixture.ToObservableChangeSet(ImmediateScheduler.Instance).Bind(out ReadOnlyObservableCollection <Unit> executed).Subscribe();

            IDisposable sub1 = fixture.Execute().Subscribe();
            IDisposable sub2 = fixture.Execute().Subscribe();
            scheduler.AdvanceByMs(999);

            Assert.True(fixture.IsExecuting.FirstAsync().Wait());
            Assert.Empty(executed);
            sub1.Dispose();

            scheduler.AdvanceByMs(2);
            Assert.Equal(1, executed.Count);
            Assert.False(fixture.IsExecuting.FirstAsync().Wait());
        });
Example #15
0
        public void ExecuteTicksThroughTheResult()
        {
            var num     = 0;
            var fixture = ReactiveCommand.CreateFromObservable(() => Observable.Return(num));

            fixture
            .ToObservableChangeSet(ImmediateScheduler.Instance).Bind(out var results).Subscribe();

            num = 1;
            fixture.Execute().Subscribe();
            num = 10;
            fixture.Execute().Subscribe();
            num = 30;
            fixture.Execute().Subscribe();

            Assert.Equal(3, results.Count);
            Assert.Equal(1, results[0]);
            Assert.Equal(10, results[1]);
            Assert.Equal(30, results[2]);
        }
Example #16
0
        public void ExceptionsAreDeliveredOnOutputScheduler()
        {
            new TestScheduler().With(sched =>
            {
                var fixture         = ReactiveCommand.CreateFromObservable(() => Observable.Throw <Unit>(new InvalidOperationException()), outputScheduler: sched);
                Exception exception = null;
                fixture
                .ThrownExceptions
                .Subscribe(ex => exception = ex);
                fixture
                .Execute()
                .Subscribe(
                    _ => { },
                    _ => { });

                Assert.Null(exception);
                sched.Start();
                Assert.IsType <InvalidOperationException>(exception);
            });
        }
Example #17
0
        public void ExecutePassesThroughParameter()
        {
            List <int> parameters = new List <int>();
            ReactiveCommand <int, Unit> fixture = ReactiveCommand.CreateFromObservable <int, Unit>(
                param =>
            {
                parameters.Add(param);
                return(Observables.Unit);
            },
                outputScheduler: ImmediateScheduler.Instance);

            fixture.Execute(1).Subscribe();
            fixture.Execute(42).Subscribe();
            fixture.Execute(348).Subscribe();

            Assert.Equal(3, parameters.Count);
            Assert.Equal(1, parameters[0]);
            Assert.Equal(42, parameters[1]);
            Assert.Equal(348, parameters[2]);
        }
Example #18
0
        public SendWhoViewModel(SendAmountViewModel savm)
            : base(Locator.Current.GetService <IViewStackService>())
        {
            Global  = Locator.Current.GetService <Global>();
            Memo    = "";
            Address = "";

            SendAmountViewModel = savm;

            var canPromptPassword = this.WhenAnyValue(x => x.Memo, x => x.Address, x => x.IsBusy,
                                                      (memo, addr, isBusy) =>
            {
                BitcoinAddress address;
                try
                {
                    address = BitcoinAddress.Create(addr.Trim(), Global.Network);
                }
                catch (FormatException)
                {
                    // SetWarningMessage("Invalid address.");
                    return(false);
                }
                return(!isBusy && memo.Length > 0 && address is BitcoinAddress);
            });

            _promptViewModel = new PasswordPromptViewModel("SEND");
            _promptViewModel.ValidatePasswordCommand.Subscribe(async validPassword =>
            {
                if (validPassword != null)
                {
                    await ViewStackService.PopModal();
                    await BuildTransaction(validPassword);
                    await ViewStackService.PushPage(new SentViewModel());
                }
            });
            PromptCommand = ReactiveCommand.CreateFromObservable(() =>
            {
                ViewStackService.PushModal(_promptViewModel).Subscribe();
                return(Observable.Return(Unit.Default));
            }, canPromptPassword);
        }
        public MessageSummaryViewModel(MessageSummary state,
                                       MessageListViewModel list,
                                       IProfileDataQueryFactory queryFactory)
        {
            _detail = new Lazy <MessageDetailViewModel>(() => new MessageDetailViewModel(state, queryFactory));
            Id      = state.Id;
            Refresh(state);

            Archive = ReactiveCommand.CreateFromObservable(() => list.Archive.Execute(new[] { Id }));

            Delete = ReactiveCommand.CreateFromObservable(() => list.Delete.Execute(new[] { Id }));

            ToggleFlag = ReactiveCommand.CreateFromObservable(() =>
            {
                var command = IsFlagged ? list.ClearFlag : list.SetFlag;
                IsFlagged   = !IsFlagged;
                return(command.Execute(new[] { Id }));
            });
            ToggleFlag.ThrownExceptions
            .ObserveOn(RxApp.MainThreadScheduler)
            .Do(_ => IsFlagged = !IsFlagged)
            .Subscribe()
            .DisposeWith(_disposables);

            ToggleRead = ReactiveCommand.CreateFromObservable(() =>
            {
                var command = IsRead ? list.MarkAsUnread : list.MarkAsRead;
                IsRead      = !IsRead;
                return(command.Execute(new[] { Id })
                       .Do(_ => _markingAsReadSubscription.Disposable = null));
            });
            ToggleRead.ThrownExceptions
            .ObserveOn(RxApp.MainThreadScheduler)
            .Do(_ => IsRead = !IsRead)
            .Subscribe()
            .DisposeWith(_disposables);

            Move = ReactiveCommand.CreateFromObservable(() => list.Move.Execute(new[] { Id }));

            MoveToJunk = ReactiveCommand.CreateFromObservable(() => list.Move.Execute(new[] { Id }));
        }
        public UserDetailsViewModel(
            UserModel model,
            IUserService userService,
            INavigationService navigationService,
            IScheduler uiScheduler)
        {
            _userService       = userService ?? throw new ArgumentNullException(nameof(userService));
            _navigationService = navigationService ?? throw new ArgumentNullException(nameof(navigationService));
            _uiScheduler       = uiScheduler ?? throw new ArgumentNullException(nameof(uiScheduler));
            _model             = model ?? throw new ArgumentNullException(nameof(model));


            _addingNewUser = String.IsNullOrWhiteSpace(_model.Id);


            SetupUserNameValidations();
            SetupPasswordValidations();


            var canSaveObs =
                this.WhenAnyValue
                (
                    x => x.ShowPasswordIsInvalid,
                    x => x.UserNameIsValid
                )
                .Select(items =>
            {
                var returnValue = !items.Item1 && items.Item2;
                return(returnValue);
            });

            canSaveObs
            .ToProperty(this, x => x.EnableSaveButton, out _enableSaveButton, scheduler: uiScheduler)
            .DisposeWith(disposable);


            SaveUser = ReactiveCommand.CreateFromObservable(SaveDetails, canExecute: canSaveObs.ObserveOn(uiScheduler));

            GoBackWithResult = ReactiveCommand.Create <UserModel, UserModel>(m => m);
            Edit             = ReactiveCommand.CreateFromObservable(() => _navigationService.UserDetailsView(_model));
        }
Example #21
0
        ReactiveCommand <Unit, Unit> InitializeCreateRepositoryCommand()
        {
            var canCreate = this.WhenAny(
                x => x.RepositoryNameValidator.ValidationResult.IsValid,
                x => x.BaseRepositoryPathValidator.ValidationResult.IsValid,
                (x, y) => x.Value && y.Value);
            var createCommand = ReactiveCommand.CreateFromObservable(OnCreateRepository, canCreate);

            createCommand.ThrownExceptions.Subscribe(ex =>
            {
                if (!Extensions.ExceptionExtensions.IsCriticalException(ex))
                {
                    log.Error(ex, "Error creating repository");
#pragma warning disable CS0618 // Type or member is obsolete
                    UserError.Throw(TranslateRepositoryCreateException(ex));
#pragma warning restore CS0618 // Type or member is obsolete
                }
            });

            return(createCommand);
        }
Example #22
0
        public SplashViewModel(IParameterViewStackService parameterViewStackService, IAppStartup appStartup)
            : base(parameterViewStackService)
        {
            _appStartup = appStartup;
            Initialize  = ReactiveCommand.CreateFromObservable(ExecuteInitialize);
            Navigate    = ReactiveCommand.CreateFromObservable(ExecuteNavigate);

            var initializing =
                this.WhenAnyObservable(x => x.Initialize.IsExecuting)
                .StartWith(false);

            initializing
            .ToProperty(this, nameof(IsLoading), out _loading)
            .DisposeWith(Subscriptions);

            initializing
            .Zip(initializing.Skip(1), (first, second) => first && !second)
            .Where(x => x)
            .Select(x => Unit.Default)
            .InvokeCommand(Navigate);
        }
        protected TestSampleViewModel()
        {
            this.tests = this
                         .GetType()
                         .GetTypeInfo()
                         .DeclaredMethods
                         .Where(method => method.IsPublic && !method.IsStatic && method.GetCustomAttribute <FactAttribute>() != null)
                         .Select((method, index) => new TestViewModel(method, this, index))
                         .ToList();

            this.executeAllTestsCommand = ReactiveCommand.CreateFromObservable(
                () => Observable.Concat(this.tests.Select(test => test.ExecuteCommand.Execute())).Select(_ => Unit.Default));

            var canExecuteSelectedTest = this
                                         .WhenAnyValue(x => x.SelectedTest)
                                         .Select(selectedTest => selectedTest != null);

            this.executeSelectedTestCommand = ReactiveCommand.CreateFromObservable(
                () => this.selectedTest.ExecuteCommand.Execute(),
                canExecuteSelectedTest);
        }
        public MainViewModel()
        {
            this.routingState = new RoutingState();

            this.startAgainCommand = ReactiveCommand.CreateFromObservable(
                () => this.routingState.NavigateAndReset.Execute(new TopicsViewModel(this)).Select(_ => Unit.Default));

            this.title = this
                         .routingState
                         .CurrentViewModel
                         .Select(x => x?.UrlPathSegment ?? null)
                         .ToProperty(this, x => x.Title);

            this.breadcrumb = this
                              .routingState
                              .CurrentViewModel
                              .Select(_ => DetermineBreadcrumb(this.routingState.NavigationStack))
                              .ToProperty(this, x => x.Breadcrumb);

            this.routingState.Navigate.Execute(new TopicsViewModel(this));
        }
Example #25
0
        public void CanExecuteIsFalseIfAlreadyExecuting()
        {
            new TestScheduler().With(
                scheduler =>
            {
                IObservable <Unit> execute           = Observables.Unit.Delay(TimeSpan.FromSeconds(1), scheduler);
                ReactiveCommand <Unit, Unit> fixture = ReactiveCommand.CreateFromObservable(() => execute, outputScheduler: scheduler);
                fixture.CanExecute.ToObservableChangeSet(ImmediateScheduler.Instance).Bind(out ReadOnlyObservableCollection <bool> canExecute).Subscribe();

                fixture.Execute().Subscribe();
                scheduler.AdvanceByMs(100);

                Assert.Equal(2, canExecute.Count);
                Assert.False(canExecute[1]);

                scheduler.AdvanceByMs(901);

                Assert.Equal(3, canExecute.Count);
                Assert.True(canExecute[2]);
            });
        }
Example #26
0
        /// <summary>
        /// Initializes a new instance of the <see cref="LoginViewModel"/> class.
        /// </summary>
        /// <param name="mainScheduler">The main scheduler.</param>
        public LoginViewModel(IScheduler mainScheduler)
        {
            Ensure.ArgumentNotNull(mainScheduler, nameof(mainScheduler));

            _mainScheduler = mainScheduler;

            var canLogin = this
                           .WhenAnyValue(
                vm => vm.UserName,
                vm => vm.Password,
                (user, password) => !string.IsNullOrWhiteSpace(user) && !string.IsNullOrWhiteSpace(password));

            Login = ReactiveCommand.CreateFromObservable(
                () =>
                Observable
                .StartAsync(LoginAsync)
                .TakeUntil(Cancel),
                canLogin, _mainScheduler);

            Cancel = ReactiveCommand.Create(() => { }, Login.IsExecuting, _mainScheduler);
        }
Example #27
0
        public void ExecuteCanBeCancelled()
        {
            (new TestScheduler()).With(sched => {
                var execute  = Observables.Unit.Delay(TimeSpan.FromSeconds(1), sched);
                var fixture  = ReactiveCommand.CreateFromObservable(() => execute, outputScheduler: sched);
                var executed = fixture
                               .CreateCollection();

                var sub1 = fixture.Execute().Subscribe();
                var sub2 = fixture.Execute().Subscribe();
                sched.AdvanceByMs(999);

                Assert.True(fixture.IsExecuting.FirstAsync().Wait());
                Assert.Empty(executed);
                sub1.Dispose();

                sched.AdvanceByMs(2);
                Assert.Equal(1, executed.Count);
                Assert.False(fixture.IsExecuting.FirstAsync().Wait());
            });
        }
Example #28
0
        public void CanExecuteIsFalseIfAlreadyExecuting()
        {
            (new TestScheduler()).With(sched => {
                var execute    = Observables.Unit.Delay(TimeSpan.FromSeconds(1), sched);
                var fixture    = ReactiveCommand.CreateFromObservable(() => execute, outputScheduler: sched);
                var canExecute = fixture
                                 .CanExecute
                                 .CreateCollection();

                fixture.Execute().Subscribe();
                sched.AdvanceByMs(100);

                Assert.Equal(2, canExecute.Count);
                Assert.False(canExecute[1]);

                sched.AdvanceByMs(901);

                Assert.Equal(3, canExecute.Count);
                Assert.True(canExecute[2]);
            });
        }
        public SettingViewModel(
            IScreen hostScreen,
            ILogger <SettingViewModel> logger,
            IConfigService configService,
            Config config,
            SourceList <RoomStatus> roomList,
            StartupService startup)
        {
            HostScreen     = hostScreen;
            _logger        = logger;
            _configService = configService;
            Config         = config;
            _roomList      = roomList;
            _startup       = startup;

            SelectMainDirCommand = ReactiveCommand.Create(SelectDirectory);
            OpenMainDirCommand   = ReactiveCommand.CreateFromObservable(OpenDirectory);
            CheckUpdateCommand   = ReactiveCommand.CreateFromTask(CheckUpdateAsync);

            InitAsync().NoWarning();
        }
Example #30
0
        // TODO: Auto fetch new posts when scrolling to the bottom of the ListView

        public AppViewModel()
        {
            Activator = new ViewModelActivator();
            Pexels    = new PexelsApi("snip");

            images.Connect().Bind(ImagesBinding).Subscribe();

            LoadPhotosCommand = ReactiveCommand.CreateFromObservable(LoadPhotos);
            LoadPhotosCommand.Subscribe(x => images.Add(x));
            LoadPhotosCommand.IsExecuting.ToPropertyEx(this, x => x.IsLoadingPhotos);

            CancelCommand = ReactiveCommand.Create(() => { }, LoadPhotosCommand.IsExecuting);

            this.WhenActivated(disposables =>
            {
                this.WhenAnyValue(x => x.ImagesBinding.Count,
                                  (int count) => $"Loaded {count} images    (last chunk took {durationMs}ms and added {addedPhotos} photos)")
                .ToPropertyEx(this, x => x.LoadedImagesText)
                .DisposeWith(disposables);
            });
        }