Esempio n. 1
0
        public HomeViewModel()
        {
            Interval           = "15";
            Title              = "Homepage";
            _weatherService    = Locator.Current.GetService <IWeatherService>();
            _dataRepository    = Locator.Current.GetService <IDataRepository>();
            _backgroundService = Locator.Current.GetService <IBackgroundService>();

            GetWeather = ReactiveCommand.CreateFromTask <string, WeatherRoot>(
                city => {
                if (string.IsNullOrEmpty(city))
                {
                    return(GetWeatherUsingGps());
                }
                return(_weatherService.GetWeather(city));
            });

            GetWeather.Subscribe(data => { Output = data; });

            _weatherService.NewWeatherUpdate.Subscribe(data => { Output = data; });

            _isLoading = GetWeather
                         .IsExecuting
                         .ToProperty(this, x => x.IsLoading);

            this.WhenValueChanged(x => x.Interval)
            .Skip(1)     // Skip initial value assignment
            .Throttle(TimeSpan.FromSeconds(2))
            .Where(x => !string.IsNullOrEmpty(x))
            .Subscribe(interval =>
            {
                _backgroundService.StopJob();
                _backgroundService.RunJob(int.Parse(interval));
            });

            GetWeather.IsExecuting
            .Skip(1)                            // IsExecuting has an initial value of false.  We can skip that first value
            .Where(isExecuting => !isExecuting) // filter until the executing state becomes false
            .Subscribe(_ => {
                if (!_backgroundService.IsJobRunning)
                {
                    _backgroundService.RunJob(int.Parse(string.IsNullOrEmpty(Interval) ? "0" : Interval));
                }
            });

            this.WhenValueChanged(x => x.Output)
            .Skip(1)     // Skip initial value assignment
            .DistinctUntilChanged()
            .Throttle(TimeSpan.FromSeconds(2))
            .Subscribe(data =>
            {
                var h = data.ToHistory();
                h.Id  = 1;
                _dataRepository.SaveItemAsync(h);
            });
        }