public override async System.Threading.Tasks.Task Load()
        {
            await base.Load();

            _itemsSource.AddRange(mockedDataGenerator.GenerateMockedPersonList(0));

            BuildAndSetObservable();
        }
Beispiel #2
0
        public void AddRange()
        {
            var people = _generator.Take(100).ToList();

            _source.AddRange(people);

            Assert.AreEqual(100, _collection.Count, "Should be 100 items in the collection");
            CollectionAssert.AreEquivalent(people, _collection, "Collections should be equivalent");
        }
Beispiel #3
0
        public void AddRange()
        {
            var people = Generator.Take(100).ToList();

            _source.AddRange(people);

            _collection.Count.Should().Be(100, "Should be 100 items in the collection");
            _collection.ShouldAllBeEquivalentTo(_collection, "Collections should be equivalent");
        }
Beispiel #4
0
        public void PropertyFilter()
        {
            var schedulerProvider = new TestSchedulerProvider();

            using (var sourceList = new SourceList <Animal>())
                using (var sut = new PropertyFilter(sourceList, schedulerProvider))
                {
                    //start the scheduler
                    schedulerProvider.TestScheduler.Start();

                    //add items
                    sourceList.AddRange(_items);
                    sut.Filtered.Count.Should().Be(0);

                    //set to true to include in the result set
                    _items[1].IncludeInResults = true;
                    _items[2].IncludeInResults = true;
                    _items[3].IncludeInResults = true;

                    //progress scheduler
                    schedulerProvider.TestScheduler.Start();

                    sut.Filtered.Items.ShouldAllBeEquivalentTo(new [] { _items[1], _items[2], _items[3] });
                }
        }
Beispiel #5
0
        public MainViewModel()
        {
            _movieService       = new MovieService();
            LoadNextPageCommand = ReactiveCommand.CreateFromTask <int, List <ShowDto> >(async _ =>
            {
                var items = await _movieService.LoadPage(_pageNr);
                await Task.Delay(1000);
                return(items);
            });

            LoadNextPageCommand.IsExecuting.BindTo(this, vm => vm.IsBusy);

            LoadNextPageCommand.Subscribe(shows =>
            {
                _showsList.AddRange(shows);
            });

            LoadNextPageCommand.Execute(_pageNr).Subscribe();

            LoadNextPageCommand.IsExecuting
            .ToProperty(this, vm => vm.IsLoadingItems, out _isLoadingItems);

            _showsList
            .Connect()
            .ObserveOn(RxApp.MainThreadScheduler)
            .Sort(SortExpressionComparer <ShowDto> .Ascending(a => a.Id))
            .Bind(Shows)
            .Subscribe();

            Shows.ShouldLoadMoreThreshold = 100;
            Shows.OnLoadMore    += OnLoadMore;
            Shows.OnCanLoadMore += OnCanLoadMore;
        }
    public ConfirmRecoveryWordsViewModel(List <RecoveryWordViewModel> mnemonicWords, KeyManager keyManager)
    {
        var confirmationWordsSourceList = new SourceList <RecoveryWordViewModel>();

        _isSkipEnable = Services.WalletManager.Network != Network.Main || System.Diagnostics.Debugger.IsAttached;

        var nextCommandCanExecute =
            confirmationWordsSourceList
            .Connect()
            .ObserveOn(RxApp.MainThreadScheduler)
            .WhenValueChanged(x => x.IsConfirmed)
            .Select(_ => confirmationWordsSourceList.Items.All(x => x.IsConfirmed));

        EnableBack = true;

        NextCommand = ReactiveCommand.Create(() => OnNext(keyManager), nextCommandCanExecute);

        if (_isSkipEnable)
        {
            SkipCommand = ReactiveCommand.Create(() => NextCommand.Execute(null));
        }

        CancelCommand = ReactiveCommand.Create(OnCancel);

        confirmationWordsSourceList
        .Connect()
        .ObserveOn(RxApp.MainThreadScheduler)
        .OnItemAdded(x => x.Reset())
        .Sort(SortExpressionComparer <RecoveryWordViewModel> .Ascending(x => x.Index))
        .Bind(out _confirmationWords)
        .Subscribe();

        // Select random words to confirm.
        confirmationWordsSourceList.AddRange(mnemonicWords.OrderBy(_ => new Random().NextDouble()).Take(3));
    }
        protected override void OnNavigatedTo(bool isInHistory, CompositeDisposable disposables)
        {
            base.OnNavigatedTo(isInHistory, disposables);

            if (!isInHistory)
            {
                var pockets = _wallet.Coins.GetPockets(_wallet.ServiceConfiguration.GetMixUntilAnonymitySetValue()).Select(x => new PocketViewModel(x));

                _pocketSource.AddRange(pockets);
            }

            foreach (var pocket in _pockets)
            {
                pocket.IsSelected = false;
            }

            if (_pocketSource.Count == 1)
            {
                _pocketSource.Items.First().IsSelected = true;

                Complete();
            }
            else if (_isSilent &&
                     _pocketSource.Items.FirstOrDefault(x => x.Labels == CoinPocketHelper.PrivateFundsText) is { } privatePocket&&
                     privatePocket.Coins.TotalAmount() >= _transactionInfo.Amount)
            {
                privatePocket.IsSelected = true;
                Complete();
            }
        }
Beispiel #8
0
        public SampleViewModel(IMessageService messageService)
        {
            this.messageService = messageService;
            WrittenText         = new Subject <object>();
            WrittenText.Subscribe(t => { });
            ShowMessageCommand = new DelegateCommand(() => messageService.ShowMessage("Saludos, colleiga!"));

            var people = new List <Person>()
            {
                new Person()
                {
                    Name    = "José Manuel",
                    Surname = "Nieto",
                },
                new Person()
                {
                    Name    = "Ana Isabel",
                    Surname = "Meana",
                },
                new Person()
                {
                    Name    = "Bichito",
                    Surname = "LG",
                }
            };

            ISourceList <object> sourceList = new SourceList <object>();

            sourceList.AddRange(people);

            People = sourceList;
        }
        public void MonitorSelectedItems(MonitorSelectedItemsMode mode)
        {
            var initialItems = Enumerable.Range(1, 10)
                               .Select(i => new SelectableItem(i))
                               .ToArray();

            //result should only be true when all items are set to true
            using (var sourceList = new SourceList <SelectableItem>())
                using (var sut = new MonitorSelectedItems(sourceList, mode))
                {
                    sourceList.AddRange(initialItems);
                    sut.HasSelection.Should().Be(false);
                    sut.SelectedMessage.Should().Be("Nothing Selected");

                    initialItems[0].IsSelected = true;
                    sut.HasSelection.Should().Be(true);
                    sut.SelectedMessage.Should().Be("1 item selected");

                    initialItems[1].IsSelected = true;
                    sut.HasSelection.Should().Be(true);
                    sut.SelectedMessage.Should().Be("2 items selected");

                    //remove the selected items
                    sourceList.RemoveRange(0, 2);
                    sut.HasSelection.Should().Be(false);
                    sut.SelectedMessage.Should().Be("Nothing Selected");
                }
        }
        public void DynamicFilter()
        {
            var schedulerProvider = new TestSchedulerProvider();

            using (var sourceList = new SourceList <Animal>())
                using (var sut = new DynamicFilter(sourceList, schedulerProvider))
                {
                    //start the scheduler
                    schedulerProvider.TestScheduler.Start();

                    //add items
                    sourceList.AddRange(_items);

                    sut.Filtered.Items.ShouldAllBeEquivalentTo(_items);
                    sut.Filtered.Count.Should().Be(_items.Length);

                    //set a filter
                    sut.AnimalFilter = "Dog";
                    schedulerProvider.TestScheduler.Start();

                    sut.Filtered.Items.ShouldAllBeEquivalentTo(_items.Where(a => a.Type == "Dog"));
                    sut.Filtered.Count.Should().Be(2);

                    //add a new dog to show it is included in the result set
                    sourceList.Add(new Animal("George", "Dog", AnimalFamily.Mammal));
                    sut.Filtered.Count.Should().Be(3);

                    //add a new bird to show it is included in the result set
                    sourceList.Add(new Animal("Peter", "Parrot", AnimalFamily.Bird));
                    sut.Filtered.Count.Should().Be(3);
                }
        }
        public void AutoRefresh()
        {
            var items = Enumerable.Range(1, 100).Select(i => new Person("Person" + i, 1)).ToArray();

            //result should only be true when all items are set to true
            using var list    = new SourceList <Person>();
            using var results = list.Connect().AutoRefresh(p => p.Age).AsAggregator();
            list.AddRange(items);

            results.Data.Count.Should().Be(100);
            results.Messages.Count.Should().Be(1);

            items[0].Age = 10;
            results.Data.Count.Should().Be(100);
            results.Messages.Count.Should().Be(2);

            results.Messages[1].First().Reason.Should().Be(ListChangeReason.Refresh);

            //remove an item and check no change is fired
            var toRemove = items[1];

            list.Remove(toRemove);
            results.Data.Count.Should().Be(99);
            results.Messages.Count.Should().Be(3);
            toRemove.Age = 100;
            results.Messages.Count.Should().Be(3);

            //add it back in and check it updates
            list.Add(toRemove);
            results.Messages.Count.Should().Be(4);
            toRemove.Age = 101;
            results.Messages.Count.Should().Be(5);

            results.Messages.Last().First().Reason.Should().Be(ListChangeReason.Refresh);
        }
Beispiel #12
0
        public void AutoRefreshGroup()
        {
            var items = Enumerable.Range(1, 100)
                        .Select(i => new Person("Person" + i, i))
                        .ToArray();

            //result should only be true when all items are set to true
            using (var list = new SourceList <Person>())
                using (var results = list.Connect()
                                     .AutoRefresh(p => p.Age)
                                     .GroupOn(p => p.Age % 10)
                                     .AsAggregator())
                {
                    void CheckContent()
                    {
                        foreach (var grouping in items.GroupBy(p => p.Age % 10))
                        {
                            var childGroup = results.Data.Items.Single(g => g.GroupKey == grouping.Key);
                            var expected   = grouping.OrderBy(p => p.Name);
                            var actual     = childGroup.List.Items.OrderBy(p => p.Name);
                            actual.ShouldAllBeEquivalentTo(expected);
                        }
                    }

                    list.AddRange(items);
                    results.Data.Count.Should().Be(10);
                    results.Messages.Count.Should().Be(1);
                    CheckContent();

                    //move person from group 1 to 2
                    items[0].Age = items[0].Age + 1;
                    CheckContent();

                    //change the value and move to a grouping which does not yet exist
                    items[1].Age = -1;
                    results.Data.Count.Should().Be(11);
                    results.Data.Items.Last().GroupKey.Should().Be(-1);
                    results.Data.Items.Last().List.Count.Should().Be(1);
                    results.Data.Items.First().List.Count.Should().Be(9);
                    CheckContent();

                    //put the value back where it was and check the group was removed
                    items[1].Age = 1;
                    results.Data.Count.Should().Be(10);
                    CheckContent();


                    var groupOf3 = results.Data.Items.ElementAt(2);

                    IChangeSet <Person> changes = null;
                    groupOf3.List.Connect().Subscribe(c => changes = c);

                    //refresh an item which makes it belong to the same group - should then propagate a refresh
                    items[2].Age = 13;
                    changes.Should().NotBeNull();
                    changes.Count.Should().Be(1);
                    changes.First().Reason.Should().Be(ListChangeReason.Replace);
                    changes.First().Item.Current.Should().BeSameAs(items[2]);
                }
        }
        public void Remove()
        {
            var tourProviders = new SourceList <TourProvider>();

            var allTours = tourProviders.Connect().TransformMany(tourProvider => tourProvider.Tours).AsObservableList();

            var tour1_1 = new Tour("Tour 1.1");
            var tour2_1 = new Tour("Tour 2.1");
            var tour2_2 = new Tour("Tour 2.2");
            var tour3_1 = new Tour("Tour 3.1");

            var tp1 = new TourProvider("Tour provider 1", new[] { tour1_1 });
            var tp2 = new TourProvider("Tour provider 2", new[] { tour2_1, tour2_2 });
            var tp3 = new TourProvider("Tour provider 3", null);

            tourProviders.AddRange(new[] { tp1, tp2, tp3 });

            allTours.Items.Should().BeEquivalentTo(tour1_1, tour2_1, tour2_2);

            tp3.Tours.Add(tour3_1);
            allTours.Items.Should().BeEquivalentTo(tour1_1, tour2_1, tour2_2, tour3_1);

            tp2.Tours.Remove(tour2_1);
            allTours.Items.Should().BeEquivalentTo(tour1_1, tour2_2, tour3_1);

            tp2.Tours.Add(tour2_1);
            allTours.Items.Should().BeEquivalentTo(tour1_1, tour2_1, tour2_2, tour3_1);
        }
Beispiel #14
0
 public Shop(IEnumerable <Product> products)
 {
     _products.AddRange(products);
     _products.Connect()
     .Bind(out readOnlyProducts)
     .Subscribe();
 }
Beispiel #15
0
        public QueryHistoryProvider()
        {
            _historySourceList = new SourceList <RawQueryHistory>();

            var counter = _historySourceList.CountChanged.Subscribe(i => IsEmpty = i == 0);

            var limiter = _historySourceList.LimitSizeTo(100).Subscribe();

            _historySourceList.AddRange(LoadFileData());

            var sharedList = _historySourceList
                             .Connect()
                             .DeferUntilLoaded()
                             .Sort(SortExpressionComparer <RawQueryHistory> .Descending(t => t.LastRunAt))
                             .ObserveOnDispatcher()
                             .Bind(out _queryHistories)
                             .Subscribe();

            var disposable = _queryHistories
                             .ObserveCollectionChanges()
                             .Throttle(TimeSpan.FromSeconds(2))
                             .Subscribe(pattern => { SaveFileData(_queryHistories); });

            _compositeDisposable = new CompositeDisposable(counter, limiter, sharedList, disposable);
        }
Beispiel #16
0
        public IObservable <Action> LoadNextMessages(
            Target target,
            SourceList <ItemModel> items)
        {
            switch (target)
            {
            case Chat chat:
                return(LoadNextMessages(chat, items)
                       .Aggregate(new List <Message>(), (list, m) =>
                {
                    list.Add(m);
                    return list;
                })
                       .Select(messages => new Action(() =>
                {
                    var models = messages
                                 .Select(_messageModelFactory.CreateMessage)
                                 .Reverse()
                                 .ToList();

                    items.AddRange(models);
                })));
            }

            return(Observable.Empty <Action>());
        }
        public void PagingListWithVirtualise()
        {
            using (var pager = new BehaviorSubject <IVirtualRequest>(new VirtualRequest(0, 0)))
                using (var sourceList = new SourceList <Animal>())
                    using (var sut = new PagingListWithVirtualise(sourceList, pager))
                    {
                        // Add items to source
                        sourceList.AddRange(_items);

                        // Requested 0 items, so no data should be returned
                        sut.Virtualised.Count.Should().Be(0);

                        // Requested 2 items starting at position 0, 2 items expected
                        pager.OnNext(new VirtualRequest(0, 2));
                        sut.Virtualised.Count.Should().Be(2);

                        // Requested 2 items starting at position 2, 2 items expected
                        pager.OnNext(new VirtualRequest(2, 2));
                        sut.Virtualised.Count.Should().Be(2);

                        // Requested 5 items starting at position 0, 5 items expected
                        pager.OnNext(new VirtualRequest(0, 5));
                        sut.Virtualised.Count.Should().Be(5);

                        // Requested 1 item starting at position 5, 1 items expected
                        pager.OnNext(new VirtualRequest(5, 1));
                        sut.Virtualised.Count.Should().Be(1);
                    }
        }
        public void GroupAndMonitorPropertyChanges()
        {
            //create manual grouping so we can guage expectations
            IEnumerable <SpeciesGroup> ManualGrouping(ISourceList <Species> items)
            {
                return(items.Items.GroupBy(i => i.Name[0]).Select(g => new SpeciesGroup(g.Key, g.ToArray())));
            }

            using (var sourceList = new SourceList <Species>())
                using (var sut = new GroupAndMonitorPropertyChanges(sourceList))
                {
                    //populate with initial data
                    var initialData = new[] { new Species("Ant"), new Species("Ape"), new Species("Bear"), new Species("Boar"), new Species("Cougar") };
                    sourceList.AddRange(initialData);

                    //Check all data has loaded
                    sut.SpeciesByLetter.Items.SelectMany(g => g.Items).ShouldAllBeEquivalentTo(initialData);
                    sut.SpeciesByLetter.Items.ShouldBeEquivalentTo(ManualGrouping(sourceList));
                    sut.SpeciesByLetter.Count.Should().Be(3);

                    //change the first letter of the data and the groupings will change
                    initialData[0].Name = "Ánt"; //change the first letter
                    sut.SpeciesByLetter.Count.Should().Be(4);

                    //assert everything
                    sut.SpeciesByLetter.Items.ShouldBeEquivalentTo(ManualGrouping(sourceList));
                }
        }
Beispiel #19
0
        public MainWindowViewModel()
        {
            sourceList = new SourceList <SimpleItem>();

            //Filling source list
            sourceList.AddRange(Enumerable.Range(1, 10).Select(i => new SimpleItem(i)));

            var viewmodel = sourceList
                            .Connect()                                        //Converting collection into observable change set
                            .Transform(item => new SimpleItemViewModel(item)) //Transforming SimpleItem into SimpleItemViewModel
                            .Publish();                                       //This method allow to have more than one subscriber

            var selectedItems = viewmodel
                                .AutoRefresh(item => item.IsSelected) //Subscribing to changes of specific property
                                .Filter(item => item.IsSelected)      //Setting predicate
                                .Sort(SortExpressionComparer <SimpleItemViewModel> .Ascending(item => item.Number))
                                                                      //.ObserveOnDispatcher()
                                .Bind(out _selectedItems)             //Converting observable sequence to ReadOnlyObservableCollection
                                .Subscribe();

            var notSelectedItems = viewmodel
                                   .AutoRefresh(item => item.IsSelected)
                                   .Filter(item => !item.IsSelected)
                                   .Sort(SortExpressionComparer <SimpleItemViewModel> .Ascending(item => item.Number))
                                   //.ObserveOnDispatcher()
                                   .Bind(out _notSelectedItems)
                                   .Subscribe();

            viewmodel.Connect(); //Receiving source sequence to subscribers
        }
        public void InspectCollectionWithObservable()
        {
            var initialItems = Enumerable.Range(1, 10)
                               .Select(i => new SimpleObjectWithObservable(i))
                               .ToArray();

            //result should only be true when all items are set to true
            using (var sourceList = new SourceList <SimpleObjectWithObservable>())
                using (var sut = new InspectCollectionWithObservable(sourceList))
                {
                    sourceList.AddRange(initialItems);
                    sut.AllActive.Should().Be(false);

                    //should remain false because
                    initialItems[0].SetIsActive(true);
                    sut.AllActive.Should().Be(false);

                    //set all items to true
                    foreach (var item in initialItems)
                    {
                        item.SetIsActive(true);
                    }
                    sut.AllActive.Should().Be(true);

                    initialItems[0].SetIsActive(false);
                    sut.AllActive.Should().Be(false);

                    sourceList.Clear();
                    sut.AllActive.Should().Be(false);
                }
        }
Beispiel #21
0
        public void AutoRefreshTransform()
        {
            var items = Enumerable.Range(1, 100)
                        .Select(i => new Person("Person" + i, i))
                        .ToArray();

            //result should only be true when all items are set to true
            using (var list = new SourceList <Person>())
                using (var results = list.Connect()
                                     .AutoRefresh(p => p.Age)
                                     .Transform((p, idx) => new TransformedPerson(p, idx))
                                     .AsAggregator())
                {
                    list.AddRange(items);

                    results.Data.Count.Should().Be(100);
                    results.Messages.Count.Should().Be(1);

                    //update an item which did not match the filter and does so after change
                    items[0].Age = 60;
                    results.Messages.Count.Should().Be(2);
                    results.Messages.Last().Refreshes.Should().Be(1);
                    results.Messages.Last().First().Item.Reason.Should().Be(ListChangeReason.Refresh);
                    results.Messages.Last().First().Item.Current.Index.Should().Be(0);

                    items[60].Age = 160;
                    results.Messages.Count.Should().Be(3);
                    results.Messages.Last().Refreshes.Should().Be(1);
                    results.Messages.Last().First().Item.Reason.Should().Be(ListChangeReason.Refresh);
                    results.Messages.Last().First().Item.Current.Index.Should().Be(60);
                }
        }
Beispiel #22
0
        public void StressIt()
        {
            var list  = new SourceList <ClassA>();
            var items = Enumerable.Range(1, 10000)
                        .Select(i => new ClassA {
                Name = i.ToString(), Child = new ClassB {
                    Age = i
                }
            })
                        .ToArray();

            list.AddRange(items);

            var sw = new Stopwatch();

            //  var factory =

            var myObservable = list.Connect()
                               .Do(_ => sw.Start())
                               .WhenPropertyChanged(a => a.Child.Age, false)
                               .Do(_ => sw.Stop())
                               .Subscribe();


            items[1].Child.Age = -1;
            Console.WriteLine($"{sw.ElapsedMilliseconds}");
        }
Beispiel #23
0
        public void AutoRefreshDistinct()
        {
            var items = Enumerable.Range(1, 100)
                        .Select(i => new Person("Person" + i, i))
                        .ToArray();

            //result should only be true when all items are set to true
            using (var list = new SourceList <Person>())
                using (var results = list.Connect()
                                     .AutoRefresh(p => p.Age)
                                     .DistinctValues(p => p.Age / 10)
                                     .AsAggregator())
                {
                    list.AddRange(items);

                    results.Data.Count.Should().Be(11);
                    results.Messages.Count.Should().Be(1);

                    //update an item which did not match the filter and does so after change
                    items[50].Age = 500;
                    results.Data.Count.Should().Be(12);

                    results.Messages.Last().First().Reason.Should().Be(ListChangeReason.Add);
                    results.Messages.Last().First().Item.Current.Should().Be(50);
                }
        }
        public AggregationViewModel()
        {
            var sourceList = new SourceList<AggregationItem>();

            sourceList.AddRange(Enumerable.Range(1, 15).Select(i => new AggregationItem(i)));

            //Load items to display to user and allow them to include items or not
         
            var listLoader = sourceList.Connect()
                .Sort(SortExpressionComparer<AggregationItem>.Ascending(vm => vm.Number))
                .ObserveOnDispatcher()
                .Bind(out _items)
                .Subscribe();

            // share the connection because we are doing multiple aggregations
            var aggregatable = sourceList.Connect()
                .FilterOnProperty(vm => vm.IncludeInTotal, vm => vm.IncludeInTotal)
                .Publish();

            //Do a custom aggregation (ToCollection() produces a readonly collection of underlying data)
            var sumOfOddNumbers = aggregatable.ToCollection()
                .Select(collection => collection.Where(i => i.Number%2 == 1).Select(ai => ai.Number).Sum())
                .Subscribe(sum => SumOfOddNumbers = sum);
            
            _cleanUp = new CompositeDisposable(sourceList, 
                listLoader,
                aggregatable.Count().Subscribe(count => Count = count),
                aggregatable.Sum(ai => ai.Number).Subscribe(sum => Sum = sum),
                aggregatable.Avg(ai => ai.Number).Subscribe(average => Avg = Math.Round(average,2)),
                aggregatable.Minimum(ai => ai.Number).Subscribe(max => Max = max),
                aggregatable.Maximum(ai => ai.Number).Subscribe(min => Min = min),
                aggregatable.StdDev(ai => ai.Number).Subscribe(std => StdDev = Math.Round(std, 2)),
                sumOfOddNumbers,
                aggregatable.Connect());
        }
Beispiel #25
0
        public void AutoRefreshSelected()
        {
            //test added as v6 broke unit test in DynamicData.Snippets
            var initialItems = Enumerable.Range(1, 10)
                               .Select(i => new SelectableItem(i))
                               .ToArray();

            //result should only be true when all items are set to true
            using (var sourceList = new SourceList <SelectableItem>())
                using (var sut = sourceList.Connect().AutoRefresh().Filter(si => si.IsSelected).AsObservableList())
                {
                    sourceList.AddRange(initialItems);
                    sut.Count.Should().Be(0);

                    initialItems[0].IsSelected = true;
                    sut.Count.Should().Be(1);

                    initialItems[1].IsSelected = true;
                    sut.Count.Should().Be(2);

                    //remove the selected items
                    sourceList.RemoveRange(0, 2);
                    sut.Count.Should().Be(0);
                }
        }
Beispiel #26
0
        public void SwitchOnTest()
        {
            SourceList <int> one   = new SourceList <int>();
            SourceList <int> other = new SourceList <int>();

            one.AddRange(new[] { 1, 3 });
            other.AddRange(new[] { 2, 4 });

            using (var switcher = new BehaviorSubject <Unit>(Unit.Default))
                using (var aggregate = switcher.Scan(other, (agg, cur) => agg == one ? other : one).Switch().AsAggregator())
                {
                    CollectionAssert.AreEqual(new [] { 1, 3 }, aggregate.Data.Items);

                    switcher.OnNext(Unit.Default);

                    CollectionAssert.AreEqual(new [] { 2, 4 }, aggregate.Data.Items);

                    one.Add(5);

                    CollectionAssert.AreEqual(new [] { 2, 4 }, aggregate.Data.Items);

                    switcher.OnNext(Unit.Default);

                    CollectionAssert.AreEqual(new [] { 1, 3, 5 }, aggregate.Data.Items);

                    other.Remove(4);

                    CollectionAssert.AreEqual(new [] { 1, 3, 5 }, aggregate.Data.Items);

                    one.Remove(3);

                    CollectionAssert.AreEqual(new [] { 1, 5 }, aggregate.Data.Items);
                }
        }
Beispiel #27
0
        public void AutoRefreshBatched()
        {
            var scheduler = new TestScheduler();

            var items = Enumerable.Range(1, 100)
                        .Select(i => new Person("Person" + i, 1))
                        .ToArray();

            //result should only be true when all items are set to true
            using (var list = new SourceList <Person>())
                using (var results = list.Connect().AutoRefresh(p => p.Age, TimeSpan.FromSeconds(1), scheduler: scheduler).AsAggregator())
                {
                    list.AddRange(items);

                    results.Data.Count.Should().Be(100);
                    results.Messages.Count.Should().Be(1);

                    //update 50 records
                    items.Skip(50)
                    .ForEach(p => p.Age = p.Age + 1);

                    scheduler.AdvanceBy(TimeSpan.FromSeconds(1).Ticks);

                    //should be another message with 50 refreshes
                    results.Messages.Count.Should().Be(2);
                    results.Messages[1].Refreshes.Should().Be(50);
                }
        }
Beispiel #28
0
        public void Test()
        {
            var a0 = new Item("A0");
            var i1 = new Item("I1");
            var i2 = new Item("I2");
            var i3 = new Item("I3");

            var obsList = new SourceList <Item>();

            obsList.AddRange(new[] { a0, i1, i2, i3 });

            var obsListDerived = obsList.Connect()
                                 .AutoRefresh(x => x.Name)
                                 .Filter(x => x.Name.Contains("I"))
                                 .AsObservableList();

            obsListDerived.Count.Should().Be(3);
            obsListDerived.Items.Should().BeEquivalentTo(new[] { i1, i2, i3 });

            i1.Name = "X2";
            obsListDerived.Count.Should().Be(2);
            obsListDerived.Items.Should().BeEquivalentTo(new[] { i2, i3 });

            a0.Name = "I0";
            obsListDerived.Count.Should().Be(3);
            obsListDerived.Items.Should().BeEquivalentTo(new[] { a0, i2, i3 });
        }
Beispiel #29
0
        public void Aggregations()
        {
            using (var dataSource = new SourceList <int>())
                using (var sut = new Aggregations(dataSource))
                {
                    //check StartWithEmpty() has taken effect
                    sut.Min.Should().NotBeNull();
                    sut.Max.Should().NotBeNull();
                    sut.Avg.Should().NotBeNull();

                    dataSource.AddRange(Enumerable.Range(1, 10));

                    sut.Min.Should().Be(1);
                    sut.Max.Should().Be(10);
                    sut.Avg.Should().Be(5.5);

                    dataSource.RemoveRange(0, 9);
                    dataSource.Add(100);

                    //items in list = [10,100]
                    sut.Min.Should().Be(10);
                    sut.Max.Should().Be(100);
                    sut.Avg.Should().Be(55);
                }
        }
        private Task Wizard(bool FSharpVersion)
        {
            cancelWizard = new CancellationTokenSource();

            // run the study plan wizard in the background on a separate thread (so that the UI remains responsive)
            return(Task.Run(() =>
            {
                if (plan.Items.Count() > 0 && StudyPlannerModel.isLegalPlan(plan.Items))
                {
                    IEnumerable <StudyPlan> wizard;
                    if (FSharpVersion)
                    {
                        wizard = FSharpSchedulingWizard.TryToImproveSchedule(plan.Items);
                    }
                    else
                    {
                        wizard = CSharpSchedulingWizard.TryToImproveSchedule(plan.Items);
                    }

                    foreach (var betterPlan in wizard)
                    {
                        Debug.Assert(StudyPlannerModel.isLegalPlan(plan.Items));
                        uiFactory.StartNew(() =>
                        {
                            // present each progressively improved study plan as they are discovered
                            plan.Clear();
                            plan.AddRange(betterPlan);
                        }, cancelWizard.Token);
                    }
                }
            }, cancelWizard.Token));
        }
        public SelectableItemsViewModel()
        {
            var sourceList = new SourceList <SimpleItem>();

            sourceList.AddRange(Enumerable.Range(1, 10).Select(i => new SimpleItem(i)));

            //create a shared list of view models
            var viewModels = sourceList
                             .Connect()
                             .Transform(simpleItem => new SimpleItemViewModel(simpleItem))
                             .Publish();

            //filter on items which are selected and populate into an observable collection

            var selectedLoader = viewModels
                                 .FilterOnProperty(vm => vm.IsSelected, vm => vm.IsSelected)
                                 .Sort(SortExpressionComparer <SimpleItemViewModel> .Ascending(vm => vm.Number))
                                 .ObserveOnDispatcher()
                                 .Bind(out _selected)
                                 .Subscribe();

            //filter on items which are not selected and populate into an observable collection
            var notSelectedLoader = viewModels
                                    .FilterOnProperty(vm => vm.IsSelected, vm => !vm.IsSelected)
                                    .Sort(SortExpressionComparer <SimpleItemViewModel> .Ascending(vm => vm.Number))
                                    .ObserveOnDispatcher()
                                    .Bind(out _notSelected)
                                    .Subscribe();

            _cleanUp = new CompositeDisposable(sourceList, selectedLoader, notSelectedLoader, viewModels.Connect());
        }