private static async void ParallelExecutionTest()
        {
            var o = Observable.CombineLatest(
                Observable.Start(() => { Console.WriteLine("Executing 1st on Thread: {0}", Thread.CurrentThread.ManagedThreadId); Thread.Sleep(5000); return("Result A"); }),
                Observable.Start(() => { Console.WriteLine("Executing 2nd on Thread: {0}", Thread.CurrentThread.ManagedThreadId); Thread.Sleep(5000); return("Result B"); }),
                Observable.Start(() => { Console.WriteLine("Executing 3rd on Thread: {0}", Thread.CurrentThread.ManagedThreadId); Thread.Sleep(5000); return("Result C"); })
                ).Finally(() => Console.WriteLine("Done!"));

            foreach (string r in await o.FirstAsync())
            {
                Console.WriteLine(r);
            }
        }
 public FormsRxPageViewModel()
 {
     _ = Observable.CombineLatest(
         Observable.FromEventPattern <PropertyChangedEventArgs>(this, nameof(PropertyChanged))
         .Where(x => x.EventArgs.PropertyName == nameof(Name)),
         Observable.FromEventPattern <PropertyChangedEventArgs>(this, nameof(PropertyChanged))
         .Where(x => x.EventArgs.PropertyName == nameof(Email)),
         Observable.FromEventPattern <PropertyChangedEventArgs>(this, nameof(PropertyChanged))
         .Where(x => x.EventArgs.PropertyName == nameof(Phone)),
         (Name, Email, Phone) => validate()
         )
         .Subscribe();
 }
Exemplo n.º 3
0
        private IObservable <ProjectSummaryReport> summaryReportFromResponse(IProjectsSummary response, long workspaceId)
        {
            IObservable <ChartSegment[]> summarySegments     = getChartSegmentsForWorkspace(response, workspaceId);
            IObservable <long[]>         projectIdsNotSynced = getProjectIdsNotSynced(response);

            var result = Observable.CombineLatest(
                summarySegments,
                projectIdsNotSynced,
                (segments, ids) => new ProjectSummaryReport(segments, ids.Length)
                );

            return(result);
        }
Exemplo n.º 4
0
        private void Sample5()
        {
            var x = Anime.Play(-5f, 5f, Easing.InOutSine(3f));

            var y = Anime.Play(0f, 3f, Easing.InOutSine(1.5f))
                    .Play(0f, Easing.InOutSine(1.5f));

            var z = Anime.Stay(0f);

            Observable.CombineLatest(x, y, z)
            .StopRecording()
            .SubscribeToPosition(cube);
        }
Exemplo n.º 5
0
 public static IObservable <TResult> Changed <TObj, TProperty1, TProperty2, TProperty3, TResult>(
     this TObj viewModel,
     Expression <Func <TObj, TProperty1> > propertyExpr1,
     Expression <Func <TObj, TProperty2> > propertyExpr2,
     Expression <Func <TObj, TProperty3> > propertyExpr3,
     Func <TProperty1, TProperty2, TProperty3, TResult> combine)
 {
     return(Observable.CombineLatest(
                viewModel.Changed(propertyExpr1),
                viewModel.Changed(propertyExpr2),
                viewModel.Changed(propertyExpr3),
                combine));
 }
Exemplo n.º 6
0
        public ItemService(IAccountService accountService)
        {
            _accountService = accountService;
            _firestore      = CrossCloudFirestore.Current.Instance;

            Item    = _item.ToReadOnlyReactivePropertySlim();
            Owner   = _owner.ToReadOnlyReactivePropertySlim();
            IsLiked = _isLiked.ToReadOnlyReactivePropertySlim();
            IsOwner = Observable.CombineLatest(Item, _accountService.UserId, (item, userId) => item != null && item.OwnerId == userId)
                      .ToReadOnlyReactivePropertySlim();
            IsLoaded   = _isLoaded.ToReadOnlyReactivePropertySlim();
            IsDeleting = _deletingNotifier.ToReadOnlyReactivePropertySlim();
        }
Exemplo n.º 7
0
 private IObservable <bool> CreateCanExecuteDealCommand()
 {
     return
         (Observable.CombineLatest(
              this.WhenAnyValue(x => x.InStoreGasStationOilDepot).Select(store => store != null),
              this.WhenAnyValue(x => x.Quantity).Select(quantity => quantity > 0),
              this.WhenAnyValue(x => x.SelectedEmployeeOtk).Select(user => user != null),
              this.WhenAnyValue(x => x.DateOfBook).Select(date => date != null),
              this.WhenAnyValue(x => x.NumberOfBook).Select(numberOfBook => !string.IsNullOrWhiteSpace(numberOfBook)),
              this.WhenAnyValue(x => x.SelectedEmployeeStore).Select(user => user != null),
              this.WhenAnyValue(x => x.CertificateQuality).Select(x => x != null),
              (a, b, c, d, e, f, g) => a && b && c && d && e && f && g));
 }
Exemplo n.º 8
0
        private Outputs()
        {
            Output.all = new List <Output>();

            departAdmin = new Output("STATIC_ADMIN_EXPEND",
                                     Root.def.economy.expend_depart_admin,
                                     Observable.CombineLatest(Depart.all.Select(x => x.adminExpendBase.obs), (IList <double> expend) => expend.Sum()).ToOBSValue());

            reportChaoting = new Output("STATIC_REPORT_CHAOTING_TAX",
                                        Root.def.economy.report_chaoting_percent,
                                        Chaoting.inst.expectMonthTaxValue);
            reportChaoting.expend = () => Chaoting.inst.ReportMonthTax(reportChaoting.currValue.Value);
        }
        public ExceptionViewModel()
        {
            Observable.CombineLatest(
                this.WhenPropertyChanged(x => x.Header),
                this.WhenPropertyChanged(x => x.Exception),
                Tuple.Create
                )
            .Subscribe(UpdateMessages)
            .DisposeWith(this);

            this.ShowEmailSupport = DefaultShowEmailSupport;
            this.SupportEmailUri  = DefaultSupportEmailUri;
        }
Exemplo n.º 10
0
        public VortexInstallerVM(InstallerVM installerVM)
        {
            Parent = installerVM;

            _TargetGame = installerVM.WhenAny(x => x.ModList.SourceModList.GameType)
                          .ToProperty(this, nameof(TargetGame));

            CanInstall = Observable.CombineLatest(
                this.WhenAny(x => x.TargetGame)
                .Select(game => VortexCompiler.IsActiveVortexGame(game)),
                installerVM.WhenAny(x => x.ModListLocation.InError),
                resultSelector: (isVortexGame, modListErr) => isVortexGame && !modListErr);
        }
        // Example3  Combine a serious elements.
        public void CombineLatest()
        {
            var o = Observable.CombineLatest(
                Observable.Start(() => { Console.WriteLine("Executing 1st on Thread: {0}", Thread.CurrentThread.ManagedThreadId); return("Result A"); }),
                Observable.Start(() => { Console.WriteLine("Executing 2nd on Thread: {0}", Thread.CurrentThread.ManagedThreadId); return("Result B"); }),
                Observable.Start(() => { Console.WriteLine("Executing 3rd on Thread: {0}", Thread.CurrentThread.ManagedThreadId); return("Result C"); })
                ).Finally(() => Console.WriteLine("Done!"));

            foreach (string r in o.First())
            {
                Console.WriteLine(r);
            }
        }
Exemplo n.º 12
0
 private IObservable <PaginatedResponse <T> > CreatePagedObservable <T>(Task <HttpResponseMessage> httpResponseMessage)
 {
     return(Observable.CombineLatest <T, HttpResponseHeaders, PaginatedResponse <T> >(
                httpResponseMessage.Result.Content.ReadAsAsync <T>().ToObservable(),
                Observable.Return(httpResponseMessage.Result.Headers),
                (x, y) => {
         return new PaginatedResponse <T> {
             Response = x,
             ContinuationToken = y.GetValues("x-ms-continuationtoken").First()
         };
     }
                ));
 }
Exemplo n.º 13
0
    public static IObservable <double> GetAverageOfLatest(this IEnumerable <IObservable <double> > sources)
    {
        int count = 1;
        var sums  = sources.Aggregate(
            (left, right) =>
        {
            //count how many satellites you have.
            count++;
            return(Observable.CombineLatest(left, right, (l, r) => l + r));
        });

        return(sums.Select(sum => sum / count));
    }
Exemplo n.º 14
0
        public MainPageViewModel()
        {
            UpdateTextCommand = Observable.CombineLatest(
                Text,
                SelectedItem,
                (text, selectedItem) => !string.IsNullOrEmpty(text) && selectedItem != null)
                                .ToReactiveCommand()
                                .WithSubscribe(() => SelectedItem.Value.Text.Value = Text.Value);

            AddListItemCommand = Text.Select(x => !string.IsNullOrEmpty(x))
                                 .ToReactiveCommand()
                                 .WithSubscribe(() => Items.Add(new ListItem(Text.Value)));
        }
Exemplo n.º 15
0
        public RoutedViewHost()
        {
            HorizontalContentAlignment = HorizontalAlignment.Stretch;
            VerticalContentAlignment   = VerticalAlignment.Stretch;

            if (RxApp.InUnitTestRunner())
            {
                ViewContractObservable = Observable.Never <string>();
                return;
            }

            var platform = RxApp.DependencyResolver.GetService <IPlatformOperations>();

            if (platform == null)
            {
                throw new Exception("Couldn't find an IPlatformOperations. This should never happen, your dependency resolver is broken");
            }

            ViewContractObservable = Observable.FromEventPattern <SizeChangedEventHandler, SizeChangedEventArgs>(x => SizeChanged += x, x => SizeChanged -= x)
                                     .Select(_ => platform.GetOrientation())
                                     .DistinctUntilChanged()
                                     .StartWith(platform.GetOrientation())
                                     .Select(x => x != null ? x.ToString() : default(string));

            var vmAndContract = Observable.CombineLatest(
                this.WhenAnyObservable(x => x.Router.CurrentViewModel),
                this.WhenAnyObservable(x => x.ViewContractObservable),
                (vm, contract) => Tuple.Create(vm, contract));

            // NB: The DistinctUntilChanged is useful because most views in
            // WinRT will end up getting here twice - once for configuring
            // the RoutedViewHost's ViewModel, and once on load via SizeChanged
            vmAndContract.DistinctUntilChanged().Subscribe(x => {
                if (x.Item1 == null)
                {
                    Content = DefaultContent;
                    return;
                }

                var viewLocator = ViewLocator ?? ReactiveUI.ViewLocator.Current;
                var view        = viewLocator.ResolveView(x.Item1, x.Item2) ?? viewLocator.ResolveView(x.Item1, null);

                if (view == null)
                {
                    throw new Exception(String.Format("Couldn't find view for '{0}'.", x.Item1));
                }

                view.ViewModel = x.Item1;
                Content        = view;
            }, ex => RxApp.DefaultExceptionHandler.OnNext(ex));
        }
Exemplo n.º 16
0
        public async Task UpdatesTreeDiff()
        {
            using var signal = new SemaphoreSlim(0, 1);

            var shaGenerator = new PseudoShaGenerator();
            var addedFile    = new TreeEntryChangesMock(ChangeKind.Added,
                                                        true, Mode.NonExecutableFile, new ObjectId(shaGenerator.Generate()), "some/p.ath",
                                                        false, Mode.Nonexistent, null, null);
            var firstCommit    = CommitMock.GenerateCommit(shaGenerator, null, 0);
            var secondCommit   = CommitMock.GenerateCommit(shaGenerator, firstCommit.Yield(), 1);
            var compareOptions = new CompareOptions();
            var diff           = new DiffMock(null, (oldTree, newTree, CompareOptions)
                                              => (oldTree, newTree, CompareOptions) == (firstCommit.Tree, secondCommit.Tree, compareOptions)
                    ? new TreeChangesMock(((TreeEntryChanges)addedFile).Yield().ToList())
                    : throw new Exception("Compare was called with wrong arguments."));
            var oldCommit         = Observable.Return(new Variant <Commit, DiffTargets>(firstCommit));
            var newCommit         = Observable.Return(new Variant <Commit, DiffTargets>(secondCommit));
            var head              = new BranchMock(true, false, null, secondCommit, "HEAD");
            var compareOptionsObs = Observable.Return(compareOptions);
            var repo              = new RepositoryMock(new CommitMock[] { firstCommit, secondCommit }, new BranchCollectionMock(head.Yield().ToList()), null, diff);
            var repoObservable    = Observable.Return(repo).Concat(Observable.Never <IRepositoryWrapper>());
            var input             = Observable
                                    .CombineLatest(oldCommit, newCommit, compareOptionsObs, repoObservable, (o, n, c, r) => new DiffViewModelInput(r, o, n, c));

            Variant <List <TreeEntryChanges>, Unexpected>?value = null;
            var vm = new DiffViewModel(new TestSchedulers(), input);

            using var _ = vm.TreeDiff
                          .Subscribe(val =>
            {
                value = val;
                if (val.Is <List <TreeEntryChanges> >())
                {
                    signal.Release();
                }
            });

            if (value is null)
            {
                value = vm.TreeDiff.Value;
            }
            if (value is null)
            {
                throw new Exception("TreeDiff was not set.");
            }
            if (!value.Is <List <TreeEntryChanges> >())
            {
                await signal.WaitAsync(TimeSpan.FromSeconds(10));
            }
            Assert.IsTrue(value.Is <List <TreeEntryChanges> >());
        }
Exemplo n.º 17
0
        /// <summary>
        /// Initializes a new instance of the <see cref="ViewModelViewHost"/> class.
        /// </summary>
        public ViewModelViewHost()
        {
            // NB: InUnitTestRunner also returns true in Design Mode
            if (ModeDetector.InUnitTestRunner())
            {
                ViewContractObservable = Observable <string> .Never;
                return;
            }

            ViewContractObservable = Observable <string> .Default;

            var vmAndContract = Observable.CombineLatest(
                this.WhenAnyValue(x => x.ViewModel),
                this.WhenAnyObservable(x => x.ViewContractObservable),
                (vm, contract) => new { ViewModel = vm, Contract = contract, });

            this.WhenActivated(() =>
            {
                return(new[]
                {
                    vmAndContract.Subscribe(x =>
                    {
                        _viewContract = x.Contract;

                        if (x.ViewModel == null)
                        {
                            Content = DefaultContent;
                            return;
                        }

                        var viewLocator = ViewLocator ?? ReactiveUI.ViewLocator.Current;
                        var view = viewLocator.ResolveView(x.ViewModel, x.Contract) ?? viewLocator.ResolveView(x.ViewModel, null);

                        if (view == null)
                        {
                            throw new Exception(string.Format("Couldn't find view for '{0}'.", x.ViewModel));
                        }

                        var castView = view as View;

                        if (castView == null)
                        {
                            throw new Exception(string.Format("View '{0}' is not a subclass of '{1}'.", view.GetType().FullName, typeof(View).FullName));
                        }

                        view.ViewModel = x.ViewModel;
                        Content = castView;
                    })
                });
            });
        }
Exemplo n.º 18
0
    /// <summary>
    /// <para>Set INotifyDataErrorInfo's asynchronous validation, return value is self.</para>
    /// </summary>
    /// <param name="validator">If success return IO&lt;null&gt;, failure return IO&lt;IEnumerable&gt;(Errors).</param>
    /// <returns>Self.</returns>
    public ReactiveProperty <T> SetValidateNotifyError(Func <IObservable <T>, IObservable <IEnumerable?> > validator)
    {
        ValidatorStore.Value.Add(validator);     //--- cache validation functions
        var validators = ValidatorStore.Value
                         .Select(x => x(IsIgnoreInitialValidationError ? ValidationTrigger : ValidationTrigger.StartWith(LatestValue)))
                         .ToArray(); //--- use copy

        ValidateNotifyErrorSubscription.Disposable = Observable
                                                     .CombineLatest(validators)
                                                     .Select(xs =>
        {
            if (xs.Count == 0)
            {
                return(null);
            }

            if (xs.All(x => x == null))
            {
                return(null);
            }

            var strings = xs
                          .Where(x => x != null)
                          .OfType <string>();
            var others = xs
                         .Where(x => x is not string)
                         .Where(x => x != null)
                         .SelectMany(x => x !.Cast <object?>());
            return(strings.Concat(others));
        })
                                                     .Subscribe(x =>
        {
            var prevHasErrors    = HasErrors;
            CurrentErrors        = x;
            var currentHasErrors = HasErrors;
            var handler          = ErrorsChanged;
            if (handler != null)
            {
                RaiseEventScheduler.Schedule(() => handler(this, SingletonDataErrorsChangedEventArgs.Value));
            }

            var propertyChangedHandler = PropertyChanged;
            if (prevHasErrors != currentHasErrors && propertyChangedHandler != null)
            {
                RaiseEventScheduler.Schedule(() => propertyChangedHandler(this, SingletonPropertyChangedEventArgs.HasErrors));
            }

            ErrorsTrigger.Value.OnNext(x);
        });
        return(this);
    }
Exemplo n.º 19
0
        public TimeEntriesViewModel(
            ITogglDataSource dataSource,
            IInteractorFactory interactorFactory,
            IAnalyticsService analyticsService,
            ISchedulerProvider schedulerProvider,
            IRxActionFactory rxActionFactory,
            ITimeService timeService)
        {
            Ensure.Argument.IsNotNull(dataSource, nameof(dataSource));
            Ensure.Argument.IsNotNull(interactorFactory, nameof(interactorFactory));
            Ensure.Argument.IsNotNull(analyticsService, nameof(analyticsService));
            Ensure.Argument.IsNotNull(schedulerProvider, nameof(schedulerProvider));
            Ensure.Argument.IsNotNull(rxActionFactory, nameof(rxActionFactory));
            Ensure.Argument.IsNotNull(timeService, nameof(timeService));

            this.interactorFactory = interactorFactory;
            this.analyticsService  = analyticsService;
            this.schedulerProvider = schedulerProvider;

            DelayDeleteTimeEntries = rxActionFactory.FromAction <long[]>(delayDeleteTimeEntries);
            ToggleGroupExpansion   = rxActionFactory.FromAction <GroupId>(toggleGroupExpansion);
            CancelDeleteTimeEntry  = rxActionFactory.FromAction(cancelDeleteTimeEntry);

            groupsFlatteningStrategy = new TimeEntriesGroupsFlattening(timeService);

            var deletingOrPressingUndo = timeEntriesPendingDeletionSubject.SelectUnit();
            var collapsingOrExpanding  = ToggleGroupExpansion.Elements;

            var visibleTimeEntries = interactorFactory.ObserveAllTimeEntriesVisibleToTheUser().Execute()
                                     .Select(timeEntries => timeEntries.Where(isNotRunning))
                                     .ReemitWhen(deletingOrPressingUndo)
                                     .Select(timeEntries => timeEntries.Where(isNotDeleted))
                                     .Select(group)
                                     .ReemitWhen(collapsingOrExpanding);

            TimeEntries = Observable.CombineLatest(
                visibleTimeEntries,
                dataSource.Preferences.Current,
                groupsFlatteningStrategy.Flatten)
                          .AsDriver(schedulerProvider);

            Empty = TimeEntries
                    .Select(groups => groups.None())
                    .AsDriver(schedulerProvider);

            Count = TimeEntries
                    .Select(log => log.Sum(day => day.Items.Count))
                    .AsDriver(schedulerProvider);

            TimeEntriesPendingDeletion = timeEntriesPendingDeletionSubject.AsObservable().AsDriver(schedulerProvider);
        }
        public RepositoryCloneViewModel(
            IOperatingSystem os,
            IConnectionManager connectionManager,
            IRepositoryCloneService service,
            IGitService gitService,
            IUsageService usageService,
            IUsageTracker usageTracker,
            IRepositorySelectViewModel gitHubTab,
            IRepositorySelectViewModel enterpriseTab,
            IRepositoryUrlViewModel urlTab)
        {
            this.os = os;
            this.connectionManager = connectionManager;
            this.service           = service;
            this.gitService        = gitService;
            this.usageService      = usageService;
            this.usageTracker      = usageTracker;

            GitHubTab     = gitHubTab;
            EnterpriseTab = enterpriseTab;
            UrlTab        = urlTab;
            tabs          = new IRepositoryCloneTabViewModel[] { GitHubTab, EnterpriseTab, UrlTab };

            var repository = this.WhenAnyValue(x => x.SelectedTabIndex)
                             .SelectMany(x => tabs[x].WhenAnyValue(tab => tab.Repository));

            Path = service.DefaultClonePath;
            repository.Subscribe(x => UpdatePath(x));

            pathWarning = Observable.CombineLatest(
                repository,
                this.WhenAnyValue(x => x.Path),
                ValidatePathWarning)
                          .ToProperty(this, x => x.PathWarning);

            var canClone = Observable.CombineLatest(
                repository, this.WhenAnyValue(x => x.Path),
                (repo, path) => repo != null && !service.DestinationFileExists(path) && !service.DestinationDirectoryExists(path));

            var canOpen = Observable.CombineLatest(
                repository, this.WhenAnyValue(x => x.Path),
                (repo, path) => repo != null && !service.DestinationFileExists(path) && service.DestinationDirectoryExists(path));

            Browse = ReactiveCommand.Create().OnExecuteCompleted(_ => BrowseForDirectory());
            Clone  = ReactiveCommand.CreateAsyncObservable(
                canClone,
                _ => repository.Select(x => new CloneDialogResult(Path, x?.CloneUrl)));
            Open = ReactiveCommand.CreateAsyncObservable(
                canOpen,
                _ => repository.Select(x => new CloneDialogResult(Path, x?.CloneUrl)));
        }
Exemplo n.º 21
0
 public static IObservable <Tuple <TProp1, TProp2, TProp3, TProp4> > WhenPropertiesChanged <TViewModel, TProp1, TProp2, TProp3, TProp4>(this TViewModel viewModel,
                                                                                                                                        Expression <Func <TViewModel, TProp1> > property1,
                                                                                                                                        Expression <Func <TViewModel, TProp2> > property2,
                                                                                                                                        Expression <Func <TViewModel, TProp3> > property3,
                                                                                                                                        Expression <Func <TViewModel, TProp4> > property4)
     where TViewModel : IObservableObject
 {
     return(Observable.CombineLatest(
                viewModel.WhenPropertyChanged(property1),
                viewModel.WhenPropertyChanged(property2),
                viewModel.WhenPropertyChanged(property3),
                viewModel.WhenPropertyChanged(property4),
                Tuple.Create));
 }
Exemplo n.º 22
0
        //private readonly Random _random = new Random((int)DateTime.Now.Ticks);

        #endregion

        #region ctor

        public PlaybackQueue(
            IAudioPlaybackEngineSync audioPlayer
            //, IObservable<IChangeSet<Track> tracksCacheChanges
            )
        {
            this._audioPlayer = audioPlayer ?? throw new ArgumentNullException(nameof(audioPlayer));

            this._isShuffleActivated_BehaviorSubject = new BehaviorSubject <bool>(false).DisposeWith(this._disposables);
            this._sourcedEntries = new SourceList <PlaybackQueueEntry>().DisposeWith(this._disposables);

            Observable.CombineLatest(
                this._audioPlayer.WhenCanLoadChanged,
                this._audioPlayer.WhenCanPlayChanged,
                (canLoad, canPlay) => canLoad && !canPlay)
            .Where(canLoadButNotPlay => canLoadButNotPlay == true)
            .Subscribe((s) =>
            {
                PlaybackQueueEntry next = null;     // = this._playlistEntries.Items.FirstOrDefault();

                this._playlistEntries.Edit(list =>
                {
                    next = list.FirstOrDefault();
                    if (next == null)
                    {
                        // unsubscribe from playlist?
                        return;
                    }
                    list.RemoveAt(0);
                });

                if (next == null)
                {
                    return;
                }

                switch (next.Track)
                {
                case Track nextTrack:
                    this._audioPlayer.LoadAndPlay(nextTrack);
                    break;
                }
            })
            .DisposeWith(this._disposables);

            //this._upNextEntries = new SourceList<PlaybackQueueEntry>().DisposeWith(this._disposables);
            this._playlistEntries = new SourceList <PlaybackQueueEntry>().DisposeWith(this._disposables);

            //this._upNextEntries.Connect().Bind(out this._upNextEntriesROOC);
            this._playlistEntries.Connect().Bind(out this._playlistEntriesROOC);
        }
Exemplo n.º 23
0
 public static IObservable <TResult> CombineVeryLatest <TLeft, TRight, TResult>(this IObservable <TLeft> leftSource, IObservable <TRight> rightSource, Func <TLeft, TRight, TResult> selector)
 {
     // code from http://stackoverflow.com/questions/3211134/how-to-throttle-event-stream-using-rx/3224723#3224723
     return(Observable.Defer(() =>
     {
         int l = -1, r = -1;                               // the last yielded index from each sequence
         return Observable.CombineLatest(
             leftSource.Select(Tuple.Create <TLeft, int>), // create a tuple which marks each item in a sequence with its index
             rightSource.Select(Tuple.Create <TRight, int>), (x, y) => new { x, y })
         .Where(t => t.x.Item2 != l && t.y.Item2 != r)     // don't yield a pair if the left or right has already been yielded
         .Do(t => { l = t.x.Item2; r = t.y.Item2; })       // record the index of the last item yielded from each sequence
         .Select(t => selector(t.x.Item1, t.y.Item1));
     }));
 }
Exemplo n.º 24
0
        public PlayerWithPageContainerViewModel(HohoemaApp hohoemaApp, HohoemaPlaylist playlist)
        {
            HohoemaPlaylist = playlist;

            IsFillFloatContent = HohoemaPlaylist
                                 .ObserveProperty(x => x.IsPlayerFloatingModeEnable)
                                 .Select(x => !x)
                                 .ToReadOnlyReactiveProperty();

            IsFillFloatContent_DelayedRead = IsFillFloatContent
                                             .Delay(TimeSpan.FromMilliseconds(300))
                                             .ToReadOnlyReactiveProperty();


            IsVisibleFloatContent = HohoemaPlaylist.ObserveProperty(x => x.IsDisplayMainViewPlayer)
                                    .ToReactiveProperty(mode: ReactivePropertyMode.DistinctUntilChanged);

            IsContentDisplayFloating = Observable.CombineLatest(
                IsFillFloatContent.Select(x => !x),
                IsVisibleFloatContent
                )
                                       .Select(x => x.All(y => y))
                                       .ToReactiveProperty();


            HohoemaPlaylist.OpenPlaylistItem += HohoemaPlaylist_OpenPlaylistItem;

            IsVisibleFloatContent
            .Where(x => !x)
            .Subscribe(x =>
            {
                ClosePlayer();
            });

            if (ApiInformation.IsApiContractPresent("Windows.Foundation.UniversalApiContract", 4))
            {
                Observable.Merge(
                    IsVisibleFloatContent.Where(x => !x),
                    IsContentDisplayFloating.Where(x => x)
                    )
                .Subscribe(async x =>
                {
                    var view = ApplicationView.GetForCurrentView();
                    if (view.IsViewModeSupported(ApplicationViewMode.CompactOverlay))
                    {
                        var result = await view.TryEnterViewModeAsync(ApplicationViewMode.Default);
                    }
                });
            }
        }
Exemplo n.º 25
0
        public HeaterBandController(IObservable <double> setTemp, IObservable <double> bandTemp, TimeSpan maxHeatingTimeWithoutControl, IObservable <double> currentTemperature, IObservable <bool> heaterMasterSwitch)
        {
            var safeTemperature = currentTemperature.Timeout(maxHeatingTimeWithoutControl);

            var temperatureAboveBand = Observable.CombineLatest(setTemp, bandTemp, safeTemperature, (set, band, current) => current > set + band);
            var temperatureBelowBand = Observable.CombineLatest(setTemp, bandTemp, safeTemperature, (set, band, current) => current < set - band);

            var turnHeaterOff = temperatureAboveBand.Where(above => above == true).Select(_ => false);
            var turnHeaterOn  = temperatureBelowBand.Where(below => below == true).Select(_ => true);

            var heaterControllerSwitch = Observable.Merge(turnHeaterOn, turnHeaterOff).DistinctUntilChanged();

            HeaterOn = Observable.CombineLatest(heaterMasterSwitch, heaterControllerSwitch, (heaterMasterState, heaterControllerState) => heaterMasterState && heaterControllerState).OnErrorResumeNext(Observable.Return(false)); // turn off heater on error
        }
Exemplo n.º 26
0
 public PatcherLogDecorator(
     IProfileNameVm profileNameProvider,
     IPatcherNameVm patcherNameVm)
 {
     _logger = Observable.CombineLatest(
         profileNameProvider.WhenAnyValue(x => x.Name),
         patcherNameVm.WhenAnyValue(x => x.Name),
         (profile, patcher) => Log.Logger
         .ForContext(FunnelNames.Patcher, patcher)
         .ForContext(FunnelNames.Profile, profile))
               .ToGuiProperty(this, nameof(Logger), Log.Logger
                              .ForContext(FunnelNames.Patcher, patcherNameVm.Name)
                              .ForContext(FunnelNames.Profile, profileNameProvider.Name), deferSubscription: true);
 }
Exemplo n.º 27
0
            public HelloWorldReactiveVM()
            {
                AddProperty <string>("FullName")
                .SubscribeTo(Observable.CombineLatest(FirstName, LastName, FullNameDelegate))
                .SubscribedBy(
                    AddProperty <int>("NameLength"), x => x.Select(name => name.Length)
                    )
                .SubscribedByAsync(
                    AddProperty <int>("NameLengthAsync").SubscribedBy(_ => PushUpdates(), out IDisposable subs),
                    async x => await GetNameLengthAsync(x));

                AddInternalProperty <string>("Internal1");
                AddInternalProperty("Internal2", 0);
            }
Exemplo n.º 28
0
        public IObservable <Vector2> OnMouseScreenClick()
        {
            var streamDown = Observable.EveryUpdate()
                             .Where(_ => Input.GetMouseButtonDown(0))
                             .Select(_ => (Vector2)Input.mousePosition);

            var streamClicked = Observable.EveryUpdate()
                                .Where(_ => Input.GetMouseButton(0))
                                .Select(_ => (Vector2)Input.mousePosition);

            return(Observable.CombineLatest(streamDown, streamClicked)
                   .Where(positions => Vector2.Distance(positions[0], _centerPosition) < _range)
                   .Select(_ => ((Vector2)Input.mousePosition - _centerPosition).normalized));
        }
Exemplo n.º 29
0
        public DetailPageViewModel(TodoUsecase todoUsecase, TodoItem item, bool isNew)
        {
            Title       = new ReactiveProperty <string>(item.Title);
            Description = new ReactiveProperty <string>(item.Description);
            IsDone      = new ReactiveProperty <bool>(item.IsDone);
            Priority    = new ReactiveProperty <int>(item.Priority);

            HasDueDate = new ReactiveProperty <bool>(item.DueDate.HasValue);
            DueDate    = new ReactiveProperty <DateTime>(item.DueDate.HasValue ? item.DueDate.Value.LocalDateTime : DateTime.Today);

            // いずれかの項目が変化したら TodoItem を作り直す
            UpdatedItem = Observable.CombineLatest(
                Title, Description, Priority, HasDueDate, DueDate,
                (title, description, priority, hasDueDate, dueDate) =>
                new TodoItem(item.Id, title, IsDone.Value, description, priority,
                             hasDueDate ? dueDate : (DateTimeOffset?)null, item.CreateDate))
                          .ToReadOnlyReactiveProperty();

            UpdatedItem.Subscribe(async x =>
            {
                await todoUsecase.Update(x);
            });

            DueDate.Subscribe(x =>
            {
                if (x == DateTime.Today)
                {
                    return;
                }
                HasDueDate.Value = true;
            });

            HasDueDate.Subscribe(x =>
            {
                System.Diagnostics.Debug.WriteLine($"{x}");
            });

            DeleteDueDateCommand.Subscribe(_ =>
            {
                HasDueDate.Value = false;
            });

            IsVisibleDone = Observable.Return(!isNew && !item.IsDone).ToReadOnlyReactiveProperty();
            DoneCommand.Subscribe(async _ =>
            {
                await todoUsecase.Done(UpdatedItem.Value);
                IsDone.Value = true;
                ClosePageRequest?.Invoke(this, Unit.Default);
            });
        }
Exemplo n.º 30
0
 private void Subscribe1()
 {
     Observable.CombineLatest(
         Observable.Interval(TimeSpan.FromSeconds(1)).Select(x =>
     {
         Debug.Log(1111);
         return(x);
     }),
         Observable.Interval(TimeSpan.FromSeconds(2))
         )
     .First()
     .Subscribe(_ => Debug.Log(2111), _ => Debug.Log(2112))
     .AddTo(this);
 }