public CountryViewModel(string name, float population, Task<IBitmap> countryFlag, double longitude, double latitude)
     : base(name, population, longitude, latitude)
 {
     this.countryFlag = countryFlag
         .ToObservable()
         .ToProperty(this, x => x.CountryFlag);
 }
Example #2
0
        public IndexViewModel(IRepository repo)
        {
            this.repo = repo;
            this.refreshCommand = ReactiveCommand.Create();

            this.repositoryStatus = this.refreshCommand.Select(u =>
            {
                return repo.RetrieveStatus(new StatusOptions() { Show = StatusShowOption.IndexAndWorkDir });
            }).ToProperty(this, vm => vm.RepositoryStatus);

            this.statusEntries = this
                .WhenAny(vm => vm.RepositoryStatus, change =>
                {
                    var status = change.GetValue();

                    return status.CreateDerivedCollection(s => s, null, null, null, this.refreshCommand);
                }).ToProperty(this, vm => vm.StatusEntries);

            var resetSignal = this.WhenAny(vm => vm.StatusEntries, change =>
             {
                 return 0;
             });

            var allEntries = this.WhenAny(vm => vm.StatusEntries, change => change.GetValue());

            this.unstagedEntries = allEntries.Select(s =>
            {
                return s.CreateDerivedCollection(i => i, i => Unstaged(i.State), null, resetSignal);
            }).ToProperty(this, vm => vm.UnstagedEntries);

            this.stagedEntries = allEntries.Select(s =>
            {
                return s.CreateDerivedCollection(i => i, i => Staged(i.State), null, resetSignal);
            }).ToProperty(this, vm => vm.StagedEntries);
        }
        public void OAPHShouldRethrowErrors()
        {
            var input = new Subject<int>();
            var sched = new TestScheduler();

            var fixture = new ObservableAsPropertyHelper<int>(input,
                _ => { }, -5, sched);

            Assert.AreEqual(-5, fixture.Value);
            (new[] { 1, 2, 3, 4 }).Run(x => input.OnNext(x));

            sched.Run();

            Assert.AreEqual(4, fixture.Value);

            input.OnError(new Exception("Die!"));

            sched.Run();

            try {
                Assert.AreEqual(4, fixture.Value);
            } catch {
                return;
            }
            Assert.Fail("We should've threw there");
        }
Example #4
0
        public MainViewModel()
        {
            _multiEngine = this.ObservableToProperty(
                Engines.Changed.Select(_ => Engines.Count > 1),
                vm => vm.MultiEngine);
            _singleEngine = this.ObservableToProperty(
                Engines.Changed.Select(_ => Engines.Count == 1),
                vm => vm.SingleEngine);
            _languages = this.ObservableToProperty(
                this.ObservableForProperty(vm => vm.SelectedEngine)
                    .Select(_ => SelectedEngine.Value.Languages),
                vm => vm.Languages);
            _languages.Subscribe(_ => EnsureLanguage());
            Engines.Changed.Subscribe(_ => EnsureEngine());

            Observable.Merge(
                this.ObservableForProperty(vm => vm.DesignTimeMode).IgnoreValues(),
                this.ObservableForProperty(vm => vm.SelectedEngine).IgnoreValues(),
                this.ObservableForProperty(vm => vm.SelectedLanguage).IgnoreValues(),
                this.ObservableForProperty(vm => vm.RazorCode).IgnoreValues())
                .ObserveOn(RxApp.DeferredScheduler)
                .Subscribe(_ => Regenerate());

            this.PropertyChanged += MainViewModel_PropertyChanged;
        }
Example #5
0
 public VisualTreeViewModel(Control root)
 {
     Nodes = VisualTreeNode.Create(root);
     _details = this.WhenAnyValue(x => x.SelectedNode)
         .Select(x => x != null ? new ControlDetailsViewModel(x.Control) : null)
         .ToProperty(this, x => x.Details);
 }
        public MiniMainWindowViewModel(ITrayMainWindowViewModel trayMainWindowViewModel) {
            TrayViewModel = trayMainWindowViewModel;
            _taskbarToolTip = this.WhenAnyValue(x => x.DisplayName, x => x.TrayViewModel.Status,
                trayMainWindowViewModel.FormatTaskbarToolTip)
                .ToProperty(this, x => x.TaskbarToolTip);
            OpenPopup = ReactiveCommand.Create();
            ShowNotification = ReactiveCommand.CreateAsyncTask(async x => (ITrayNotificationViewModel) x);
            Deactivate = ReactiveCommand.Create().DefaultSetup("Deactivate");
            Deactivate.Subscribe(x => {
                if (TrayViewModel.MainArea is IWelcomeViewModel)
                    return;
                Close.Execute(null);
            });

            OpenPopup
                .Take(1)
                .Delay(TimeSpan.FromSeconds(20))
                .ObserveOnMainThread()
                .Subscribe(x => TrayViewModel.RemoveUpdatedState());

            // TODO: Make this a setting?
            /*            Listen<ApiUserActionStarted>()
                .ObserveOnMainThread()
                .InvokeCommand(OpenPopup);*/
            Listen<AppStateUpdated>()
                .Where(x => x.UpdateState == AppUpdateState.Updating)
                .ObserveOnMainThread()
                .InvokeCommand(OpenPopup);
            Listen<ShowTrayNotification>()
                .Select(x => new TrayNotificationViewModel(x.Subject, x.Text, x.CloseIn, x.Actions))
                .ObserveOnMainThread()
                .InvokeCommand(ShowNotification);
        }
 public ClientAnnotationViewModel(ISharedDataService sharedDataService, MeetingViewModel meeting) : base(sharedDataService, meeting)
 {
     // create the client annotations property, a mapped version of the agent's properties based on the screen sizes.
     _annotationsChangedSub = _clientAnnotations = AnnotationsModel
                                                       .WhenAnyValue(v => v.Annotations, v => v.Select(p => CreateAnnotationViewModel(p)))
                                                       .ToProperty(this, v => v.Annotations);
 }
        public MainWindowViewModel()
        {
            var whenAnyColorChanges = this.WhenAny(x => x.Red, x => x.Green, x => x.Blue,
                    (r, g, b) => Tuple.Create(r.Value, g.Value, b.Value))
                .Select(intsToColor);

            _FinalColor = whenAnyColorChanges
                .Where(x => x != null)
                .Select(x => x.Value)
                .ToProperty(this, x => x.FinalColor);

            Ok = ReactiveCommand.Create(whenAnyColorChanges.Select(x => x != null));

            _Images = this.WhenAny(x => x.FinalColor, x => x.Value)
                .Throttle(TimeSpan.FromSeconds(0.7), RxApp.MainThreadScheduler)
                .Do(_ => IsBusy = true)
                .Select(x => imagesForColor(x))
                .Switch()
                .SelectMany(imageListToImages)
                .ObserveOn(RxApp.MainThreadScheduler)
                .Do(_ => IsBusy = false)
                .ToProperty(this, x => x.Images);

            _Images.ThrownExceptions.Subscribe(ex => this.Log().WarnException("Can't load images", ex));
        }
 public SoundCloudSongViewModel(SoundCloudSong model)
     : base(model)
 {
     this.hasThumbnail = this.WhenAnyValue(x => x.Thumbnail)
         .Select(x => x != null)
         .ToProperty(this, x => x.HasThumbnail);
 }
        public GistCreationViewModel(
            IRepositoryHost repositoryHost,
            ISelectedTextProvider selectedTextProvider,
            IGistPublishService gistPublishService,
            IUsageTracker usageTracker)
        {
            Title = Resources.CreateGistTitle;
            apiClient = repositoryHost.ApiClient;
            this.gistPublishService = gistPublishService;
            this.usageTracker = usageTracker;

            FileName = VisualStudio.Services.GetFileNameFromActiveDocument() ?? Resources.DefaultGistFileName;
            SelectedText = selectedTextProvider.GetSelectedText();

            // This class is only instantiated after we are logged into to a github account, so we should be safe to grab the first one here as the defaut.
            account = repositoryHost.ModelService.GetAccounts()
                .FirstAsync()
                .Select(a => a.First())
                .ObserveOn(RxApp.MainThreadScheduler)
                .ToProperty(this, vm => vm.Account);

            var canCreateGist = this.WhenAny( 
                x => x.FileName,
                fileName => !String.IsNullOrEmpty(fileName.Value));

            CreateGist = ReactiveCommand.CreateAsyncObservable(canCreateGist, OnCreateGist);
        }
Example #11
0
        public MyIssuesViewModel(ISessionService sessionService)
            : base(sessionService)
        {
            _sessionService = sessionService;

            Title = "My Issues";
            Filter = MyIssuesFilterModel.CreateOpenFilter();

            _selectedFilter = this.WhenAnyValue(x => x.Filter)
                .Select(x =>
                {
                    if (x == null || _openFilter.Equals(x))
                        return 0;
                    return _closedFilter.Equals(x) ? 1 : -1;
                })
                .ToProperty(this, x => x.SelectedFilter);

            this.WhenAnyValue(x => x.Filter).Skip(1).Subscribe(filter => {
                InternalItems.Clear();
                LoadCommand.ExecuteIfCan();
                CustomFilterEnabled = !(filter == _closedFilter || filter == _openFilter);
            });

            GoToFilterCommand = ReactiveCommand.Create();
            GoToFilterCommand.Subscribe(_ => {
                var vm = this.CreateViewModel<MyIssuesFilterViewModel>();
                vm.Init(Filter);
                vm.SaveCommand.Subscribe(filter => Filter = filter);
                NavigateTo(vm);
            });
        }
Example #12
0
        public Threshold(IObservable<int> thresholdState)
        {
            //this.WhenAny(vm => vm.Good, vm => vm.Bad, vm => vm.OK, (g, b, o) =>
            //{

            //});

            this.Good = new Range();
            this.Bad = new Range();
            this.OK = new Range();

            var obs = thresholdState.Select(value =>
               {
                   if (value.Between(this.Good.Min, this.Good.Max))
                       return "Good";

                   if (value.Between(this.OK.Min, this.ok.Max))
                       return "OK";

                   if (value.Between(this.Bad.Min, this.bad.Max))
                       return "Bad";

                   return "";
               });

            this.state = obs.ToProperty(this, vm => vm.State);
            obs.Subscribe(_ =>
            {
                Trace.WriteLine(_);
            });
        }
Example #13
0
        public OAuthFlowLoginViewModel(
            IAccountsRepository accountsRepository,
            IActionMenuFactory actionMenuService,
            IAlertDialogFactory alertDialogService)
        {
            _accountsRepository = accountsRepository;
            _alertDialogService = alertDialogService;

            Title = "Login";

            var oauthLogin = ReactiveCommand.Create().WithSubscription(_ =>
                NavigateTo(this.CreateViewModel<OAuthTokenLoginViewModel>()));

            var canLogin = this.WhenAnyValue(x => x.Code).Select(x => !string.IsNullOrEmpty(x));
            var loginCommand = ReactiveCommand.CreateAsyncTask(canLogin,_ => Login(Code));
            loginCommand.Subscribe(x => MessageBus.Current.SendMessage(new LogoutMessage()));
            LoginCommand = loginCommand;

            ShowLoginOptionsCommand = ReactiveCommand.CreateAsyncTask(sender =>
            {
                var actionMenu = actionMenuService.Create();
                actionMenu.AddButton("Login via Token", oauthLogin);
                return actionMenu.Show(sender);
            });

            _loginUrl = this.WhenAnyValue(x => x.WebDomain)
                .IsNotNull()
                .Select(x => x.TrimEnd('/'))
                .Select(x => 
                    string.Format(x + "/login/oauth/authorize?client_id={0}&redirect_uri={1}&scope={2}", 
                    ClientId, Uri.EscapeDataString(RedirectUri), Uri.EscapeDataString(string.Join(",", OctokitClientFactory.Scopes))))
                .ToProperty(this, x => x.LoginUrl);

            WebDomain = DefaultWebDomain;
        }
        public SettingsViewModel(
            IScreen screen,
            ISettingsProvider settingsProvider,
            IFolderHelper folderHelper, 
            IAppContext appContext)
        {
            HostScreen = screen;

            BackCommand = new ReactiveAsyncCommand();
            BackCommand.RegisterAsyncAction(_ => HostScreen.Router.NavigateBack.Execute(null));

            SelectFolder = new ReactiveAsyncCommand();
            SelectFolder.RegisterAsyncAction(_ =>
            {
                var result = folderHelper.SelectFolder();
                if (result.Result == true) {
                    UpdateLocation = result.Folder;
                }
            }, appContext.DispatcherScheduler);

            UpdateLocation = settingsProvider.UpdateLocation;

            _IsError = this.WhenAny(vm => vm.UpdateLocation, vm => vm.Value)
                           .DistinctUntilChanged()
                           .Throttle(TimeSpan.FromMilliseconds(500))
                           .ObserveOn(appContext.DispatcherScheduler)
                           .Select(text => !IsUrlOrFolder(text))
                           .Do(error => {
                                if (!error) {
                                    settingsProvider.UpdateLocation = UpdateLocation;
                                }
                            })
                            .ToProperty(this, vm => vm.IsError, setViaReflection: false);
        }
Example #15
0
 public TreePageViewModel(TreeNode[] nodes)
 {
     Nodes = nodes;
     _details = this.WhenAnyValue(x => x.SelectedNode)
         .Select(x => x != null ? new ControlDetailsViewModel(x.Control) : null)
         .ToProperty(this, x => x.Details);
 }
Example #16
0
        /// <summary>
        /// Initializes a new instance of the <see cref="PlaylistViewModel" /> class.
        /// </summary>
        /// <param name="playlist">The playlist info.</param>
        /// <param name="renameRequest">
        /// A function that requests the rename of the playlist. Return true, if the rename is
        /// granted, otherwise false.
        /// </param>
        public PlaylistViewModel(Playlist playlist, Func<string, bool> renameRequest)
        {
            this.playlist = playlist;
            this.renameRequest = renameRequest;

            this.disposable = new CompositeDisposable();

            this.entries = playlist
                .CreateDerivedCollection(entry => new PlaylistEntryViewModel(entry))
                .DisposeWith(this.disposable);
            this.entries.ItemsRemoved.Subscribe(x => x.Dispose());

            this.playlist.WhenAnyValue(x => x.CurrentSongIndex).ToUnit()
                .Merge(this.entries.Changed.ToUnit())
                .Subscribe(_ => this.UpdateCurrentSong())
                .DisposeWith(this.disposable);

            IObservable<List<PlaylistEntryViewModel>> remainingSongs = this.entries.Changed
                .Select(x => Unit.Default)
                .Merge(this.playlist.WhenAnyValue(x => x.CurrentSongIndex).ToUnit())
                .Select(x => this.entries.Reverse().TakeWhile(entry => !entry.IsPlaying).ToList());

            this.songsRemaining = remainingSongs
                .Select(x => x.Count)
                .ToProperty(this, x => x.SongsRemaining)
                .DisposeWith(this.disposable);

            this.timeRemaining = remainingSongs
                .Select(x => x.Any() ? x.Select(entry => entry.Duration).Aggregate((t1, t2) => t1 + t2) : (TimeSpan?)null)
                .ToProperty(this, x => x.TimeRemaining)
                .DisposeWith(this.disposable);

            this.CurrentPlayingEntry = this.Model.WhenAnyValue(x => x.CurrentSongIndex).Select(x => x == null ? null : this.entries[x.Value]);
        }
        public AgentAnnotationViewModel(ISharedDataService sharedDataService, MeetingViewModel meeting)
            : base(sharedDataService, meeting)
        {
            _annotations = new ReactiveList<AnnotationViewModel>();

            var annotationsChangedObs = _annotations
                .WhenAnyObservable(p => p.Changed)
                .Select(p => AreThereAnnotationInTheCurrentPage());

            var activeToolObs = Meeting.WhenAnyValue(vm => vm.ActiveTool).Where(t => t != null);
            var pageChangedObs = activeToolObs
                             .Select(t => t.WhenAnyValue(v => v.CurrentPageNumber, p => AreThereAnnotationInTheCurrentPage()))
                             .Switch(); // Only listen to the most recent sequence of property changes (active tool)
            var toolChangedObs = activeToolObs.Select(t => AreThereAnnotationInTheCurrentPage());

            _containsAnnotationsForCurrentPage = toolChangedObs.Merge(pageChangedObs).Merge(annotationsChangedObs)
                .ToProperty(this, p => p.ContainsAnnotationsForCurrentPage); 

            AnnotationTools = new AnnotationToolViewModel(this);

            // when the IsEditing flag changes to false, it means an edit has just completed and we can send
            // the updates annotations to the client
            _isEditingSub = this.WhenAnyValue(p => p.IsEditing)
                .Where(p => !p)
                .Subscribe(_ => UpdateAnnotationModelAnnotations());
        }
Example #18
0
        public CreateFileViewModel(ISessionService applicationService, IAlertDialogFactory alertDialogFactory)
        {
            Title = "Create File";

            this.WhenAnyValue(x => x.Name).Subscribe(x => CommitMessage = "Created " + x);

            _canCommit = this.WhenAnyValue(x => x.Name)
                .Select(x => !string.IsNullOrEmpty(x))
                .ToProperty(this, x => x.CanCommit);

            SaveCommand = ReactiveCommand.CreateAsyncTask(
                this.WhenAnyValue(x => x.Name).Select(x => !string.IsNullOrEmpty(x)), 
                async _ =>
            {
                var content = Content ?? string.Empty;

                var path = Path;
                if (string.IsNullOrEmpty(Path))
                    path = "/";
                path = System.IO.Path.Combine(path, Name);
                var request = applicationService.Client.Users[RepositoryOwner].Repositories[RepositoryName].UpdateContentFile(path, CommitMessage, content, null, Branch);
                await applicationService.Client.ExecuteAsync(request);
                Dismiss();
            });

            DismissCommand = ReactiveCommand.CreateAsyncTask(async t =>
            {
                if (string.IsNullOrEmpty(Name) && string.IsNullOrEmpty(Content)) return true;
                return await alertDialogFactory.PromptYesNo("Discard File?", "Are you sure you want to discard this file?");
            });
            DismissCommand.Where(x => x).Subscribe(_ => Dismiss());
        }
        public InsertGistViewModel()
        {
            //var client = new GitHubClient() { Username = "octocat", Password = "FillMeInHere" };

            var privateImage = new BitmapImage(new Uri(@"pack://application:,,,/data/private.png"));
            var publicImage = new BitmapImage(new Uri(@"pack://application:,,,/data/public.png"));

            _PublicPrivateIcon = this.WhenAny(x => x.IsPrivateGist, x => x.Value)
                .Select(x => x ? privateImage : publicImage)
                .ToProperty(this, x => x.PublicPrivateIcon);

            CreateGist = new ReactiveAsyncCommand();

            CreateGist.RegisterAsyncObservable(_ => client.CreateGist(SelectionText, !IsPrivateGist))
                .Select(x => x.html_url)
                .BindTo(this, x => x.LastGistUrl);

            CopyToClipboard = new ReactiveCommand(
                this.WhenAny(x => x.LastGistUrl, x => !String.IsNullOrWhiteSpace(x.Value)));

            CopyToClipboard.Subscribe(_ => Clipboard.SetText(LastGistUrl));

            this.WhenAny(x => x.SelectionText, x => x.Value)
                .Where(_ => LastGistUrl != null)
                .Subscribe(_ => LastGistUrl = null);
        }
 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"));
 }
        public DevToolsViewModel(IControl root)
        {
            _logicalTree = new TreePageViewModel(LogicalTreeNode.Create(root));
            _visualTree = new TreePageViewModel(VisualTreeNode.Create(root));

            this.WhenAnyValue(x => x.SelectedTab).Subscribe(index =>
            {
                switch (index)
                {
                    case 0:
                        Content = _logicalTree;
                        break;
                    case 1:
                        Content = _visualTree;
                        break;
                }
            });

            _focusedControl = KeyboardDevice.Instance
                .WhenAnyValue(x => x.FocusedElement)
                .Select(x => x?.GetType().Name)
                .ToProperty(this, x => x.FocusedControl);

            _pointerOverElement = root.GetObservable(TopLevel.PointerOverElementProperty)
                .Select(x => x?.GetType().Name)
                .ToProperty(this, x => x.PointerOverElement);
        }
        public YoutubeSongViewModel(YoutubeSong wrapped, Func<string> downloadPathFunc)
            : base(wrapped)
        {
            this.hasThumbnail = this.WhenAnyValue(x => x.Thumbnail)
                .Select(x => x != null)
                .ToProperty(this, x => x.HasThumbnail);

            // Wait for the opening of the context menu to download the YouTube information
            this.WhenAnyValue(x => x.IsContextMenuOpen)
                .FirstAsync(x => x)
                .SelectMany(_ => this.LoadContextMenu().ToObservable())
                .Subscribe();

            // We have to set a dummy here, so that we can connect the commands
            this.isDownloading = Observable.Never<bool>().ToProperty(this, x => x.IsDownloading);

            this.DownloadVideoCommand = ReactiveCommand.CreateAsyncTask(this.WhenAnyValue(x => x.IsDownloading).Select(x => !x),
                x => this.DownloadVideo((VideoInfo)x, downloadPathFunc()));

            this.DownloadAudioCommand = ReactiveCommand.CreateAsyncTask(this.WhenAnyValue(x => x.IsDownloading).Select(x => !x),
                x => this.DownloadAudio((VideoInfo)x, downloadPathFunc()));

            this.isDownloading = this.DownloadVideoCommand.IsExecuting
                .CombineLatest(this.DownloadAudioCommand.IsExecuting, (x1, x2) => x1 || x2)
                .ToProperty(this, x => x.IsDownloading);
        }
        public TrayMainWindowViewModel(IViewModel mainArea, TrayMainWindowMenu menu, IStatusViewModel status,
            LoginInfo loginInfo, IWelcomeViewModel welcomeViewModel) {
            _mainArea = Consts.FirstRun /* || Cheat.Consts.IsTestVersion */ ? welcomeViewModel : mainArea;
            _menu = menu;
            _status = status;
            _loginInfo = loginInfo;

            welcomeViewModel.Close.Subscribe(x => MainArea = mainArea);

            _taskbarToolTip = this.WhenAnyValue(x => x.DisplayName, x => x.Status, FormatTaskbarToolTip)
                .ToProperty(this, x => x.TitleToolTip);

            _avatarUrl = this.WhenAnyValue<TrayMainWindowViewModel, Uri, AccountInfo>(x => x.LoginInfo.Account,
                x => new Uri("http:" + AvatarCalc.GetAvatarURL(x)))
                .ToProperty(this, x => x.AvatarUrl);

            _installUpdate =
                ReactiveCommand.CreateAsyncTask(
                    this.WhenAnyValue(x => x.UpdateState, state => state == AppUpdateState.UpdateAvailable),
                    async x => await RequestAsync(new OpenWebLink(ViewType.Update)).ConfigureAwait(false))
                    .DefaultSetup("InstallUpdate");
            _goAccount =
                ReactiveCommand.CreateAsyncTask(
                    async x => await RequestAsync(new OpenWebLink(ViewType.Profile)).ConfigureAwait(false))
                    .DefaultSetup("OpenProfile");
            _goPremium =
                ReactiveCommand.CreateAsyncTask(
                    async x =>
                        await
                            RequestAsync(
                                new OpenWebLink(_loginInfo.IsPremium ? ViewType.PremiumAccount : ViewType.GoPremium))
                                .ConfigureAwait(false))
                    .DefaultSetup("GoPremium");

            IViewModel previousMain = null;

            _switchQueue = ReactiveCommand.CreateAsyncTask(
                async x => {
                    if (previousMain == null) {
                        previousMain = _mainArea;
                        MainArea = await RequestAsync(new GetQueue()).ConfigureAwait(false);
                    } else {
                        MainArea = previousMain;
                        previousMain = null;
                    }
                });
            status.SwitchQueue = _switchQueue; // TODO..

            Listen<LoginChanged>()
                .Select(x => x.LoginInfo)
                .ObserveOnMainThread()
                .BindTo(this, x => x.LoginInfo);
            // We need to receive these right away..
            // toDO: Think about how to make this only on WhenActivated
            Listen<AppStateUpdated>()
                .Select(x => x.UpdateState)
                .ObserveOnMainThread()
                .BindTo(this, x => x.UpdateState);
        }
        public DownloadVM(
            IDiversityServiceClient Service,
            IConnectivityService Connectivity,
            IFieldDataService Storage,
            IKeyMappingService Mappings,
            EventHierarchyLoader HierarchyLoader,
            [Dispatcher] IScheduler Dispatcher
            ) {
            this.Service = Service;
            this.Connectivity = Connectivity;
            this.Storage = Storage;
            this.Mappings = Mappings;
            this.HierarchyLoader = HierarchyLoader;

            QueryResult = new ReactiveCollection<Event>();

            _IsOnlineAvailable = Connectivity.Status().Select(s => s == ConnectionStatus.Wifi).Do(_ => { this.GetType(); }, ex => { }, () => { })
                .ToProperty(this, x => x.IsOnlineAvailable);

            SearchEvents = new ReactiveAsyncCommand(this.WhenAny(x => x.IsOnlineAvailable, x => x.Value));
            SearchEvents.ShowInFlightNotification(Notifications, DiversityResources.Download_SearchingEvents);
            SearchEvents.ThrownExceptions
                    .ShowServiceErrorNotifications(Notifications)
                    .ShowErrorNotifications(Notifications)
                    .Subscribe();
            SearchEvents
                .RegisterAsyncObservable(query =>
                    Service.GetEventsByLocality(query as string ?? string.Empty)
                    .TakeUntil(this.OnDeactivation())
                )
                .Do(_ => QueryResult.Clear())
                .Subscribe(QueryResult.AddRange);

            CancelDownload = new ReactiveCommand();

            DownloadElement = new ReactiveAsyncCommand(this.WhenAny(x => x.IsOnlineAvailable, x => x.Value));
            DownloadElement.ThrownExceptions
                .ShowServiceErrorNotifications(Notifications)
                .ShowErrorNotifications(Notifications)
                .Subscribe();
            DownloadElement
                .RegisterAsyncObservable(ev => IfNotDownloadedYet(ev as Event)
                    .Select(HierarchyLoader.downloadAndStoreDependencies)
                    .SelectMany(dl => dl.TakeUntil(CancelDownload))
                    .Scan(0, (acc, _) => ++acc)
                    .Do(_ElementsDownloadedSubject.OnNext)
                    );

            _IsDownloading = DownloadElement.ItemsInflight
                .Select(x => x > 0)
                .ToProperty(this, x => x.IsDownloading);

            this.OnDeactivation()
                .Subscribe(_ => Messenger.SendMessage(EventMessage.Default, MessageContracts.INIT));

            _ElementsDownloadedSubject = new Subject<int>();
            _ElementsDownloaded = _ElementsDownloadedSubject.ToProperty(this, x => x.ElementsDownloaded, 0, Dispatcher);
        }
 public CachingStateVm(CachingState cachingState)
 {
     _cachingState = cachingState;
     var progress = cachingState.Progress;
     _finalSize = progress.Select(x => x.Total).ToProperty(this, x => x.FinalSize);
     _cachedSize = progress.Select(x => x.Current).ToProperty(this, x => x.CachedSize);
     _isFullyCached = progress.Select(x => x.Current != 0UL && x.Current == x.Total).ToProperty(this, x => x.IsFullyCached, false);
     _isInitialized = this.WhenAny(x => x.FinalSize, ch => ch.Value > 0).ToProperty(this, x => x.IsInitialized, false);
 }
 public SettingsViewModel(IEnumerable<ISettingsTabViewModel> settingsTabs) {
     var settings = settingsTabs.OrderBy(GetOrder).ToArray();
     Settings = new SelectionCollectionHelper<ISettingsTabViewModel>(settings) {
         SelectedItem = settings.FirstOrDefault()
     };
     _valid = settings.Select(x => x.WhenAnyValue(s => s.IsValid))
         .CombineLatest(x => x.All(b => b))
         .ToProperty(this, x => x.Valid);
 }
        public ViewModelViewHost()
        {
            this.currentView = new SerialDisposable();
            this.viewContract = this
                .WhenAnyObservable(x => x.ViewContractObservable)
                .ToProperty(this, x => x.ViewContract, scheduler: RxApp.MainThreadScheduler);

            this.Initialize();
        }
        public DispatchViewModel(IScreen screen, ISession session)
        {
            HostScreen = screen;
            GoBack = HostScreen.Router.NavigateBack;

            Techs = new ReactiveList<Employee>();
            Tickets = new ReactiveList<Ticket>();

            var getFreshTechs = new ReactiveCommand();
            getFreshTechs.ObserveOn(RxApp.MainThreadScheduler).Subscribe(_ =>
                {
                    Techs.Clear();
                    session.FetchResults<Employee>()
                        .ObserveOn(RxApp.MainThreadScheduler)
                        .Subscribe(x => Techs.Add(x));
                });

            var getFreshTickets = new ReactiveCommand();
            getFreshTickets.ObserveOn(RxApp.MainThreadScheduler).Subscribe(_ =>
                {
                    Tickets.Clear();
                    session.FetchResults<Ticket>()
                        .ObserveOn(RxApp.MainThreadScheduler)
                        .Subscribe(x => Tickets.Add(x));
                });

            Refresh = new ReactiveCommand(session.IsWorking.Select(x => !x));
            Refresh.Subscribe(_ =>
                {
                    getFreshTechs.Execute(default(object));
                    getFreshTickets.Execute(default(object));
                });

            Assign = new ReactiveCommand(Observable.CombineLatest(
                this.WhenAny(
                    x => x.SelectedEmployee,
                    y => y.SelectedTicket,
                    (x, y) => x.Value != null && y.Value != null),
                Refresh.CanExecuteObservable,
                (x, y) => x && y));
            Assign.Subscribe(_ =>
            {
                using (session.ScopedChanges())
                {
                    var eventTaker = session.Take<TicketEvent>();
                    eventTaker.Add(new TicketEvent { Employee = SelectedEmployee, Ticket = SelectedTicket, TicketStatus = TicketStatus.Assigned, Time = DateTime.Now });
                }
            });

            _error = session.ThrownExceptions
                .Select(x => x.Message)
                .ObserveOn(RxApp.MainThreadScheduler)
                .ToProperty(this, x => x.Error);

            Refresh.Execute(default(object));
        }
        public MainWindowViewModel(ILeapMotionService leapMotionService)
        {
            this.leapMotionService = leapMotionService;

            this._fingersDetected = leapMotionService.FingersDetected.ToProperty(this, x => x.FingersDetected);
            this.Disposables.Add(this._fingersDetected);

            this._velocity = leapMotionService.SmoothedVelocity.ToProperty(this, x => x.Velocity);
            this.Disposables.Add(this._velocity);
        }
        protected override void OnInitialize() {
            base.OnInitialize();

            _selectedItem = _mvm.Value.LibraryVM.WhenAnyValue(x => x.SelectedItem.SelectedItem)
                .OfType<IMod>()
                .ToProperty(this, x => x.SelectedItem);

            _isInCollection = this.WhenAny(x => x.SelectedItem, x => x.Value is ToggleableModProxy)
                .ToProperty(this, x => x.IsInCollection);
        }