Last active
January 10, 2022 10:51
-
-
Save RolandPheasant/6a76877802bd5990b55a3bd766aa63d2 to your computer and use it in GitHub Desktop.
Grouping fixed
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using DynamicData; | |
using DynamicData.Binding; | |
using ReactiveUI; | |
using ReactiveUI_GroupingIssueTest_Wpf.Enums; | |
using ReactiveUI_GroupingIssueTest_Wpf.Models; | |
using System; | |
using System.Collections.ObjectModel; | |
using System.Linq; | |
using System.Reactive.Linq; | |
namespace ReactiveUI_GroupingIssueTest_Wpf.ViewModels | |
{ | |
public class TestViewModel : ReactiveObject | |
{ | |
private readonly Random rnd; | |
private readonly SourceCache<Male, int> cache; | |
private readonly ReadOnlyObservableCollection<GroupTansformed> maleGroups; | |
public ReadOnlyObservableCollection<GroupTansformed> MaleGroups => maleGroups; | |
public TestViewModel() | |
{ | |
rnd = new Random(); | |
cache = new SourceCache<Male, int>(male=> male.Id); | |
cache.AddOrUpdate(Enumerable.Range(1, 11).Select(i => new Male(i, Greek.Alpha))); | |
cache.Connect() | |
.AutoRefresh(male => male.FavouriteGreekLetter) | |
.Group(male => male.FavouriteGreekLetter) | |
.Transform(group => new GroupTansformed(group)) | |
.ObserveOn(RxApp.MainThreadScheduler) | |
.Bind(out maleGroups) | |
.DisposeMany() // When a group is deleted we need to dispose it | |
.Subscribe(); | |
Observable.Interval(TimeSpan.FromSeconds(1)) | |
.Select(s => cache.Items.Skip(rnd.Next(0, cache.Count)).FirstOrDefault()) | |
.WhereNotNull() | |
.Do(male => male.FavouriteGreekLetter = Enum.GetValues(typeof(Greek)).OfType<Greek>().OrderBy(e => Guid.NewGuid()).FirstOrDefault()) | |
.Subscribe(); | |
} | |
} | |
public class GroupTansformed : AbstractNotifyPropertyChanged | |
{ | |
private readonly IDisposable _cleanUp; | |
public Greek Key { get; } | |
private int _count; | |
public int Count | |
{ | |
get => _count; | |
set => SetAndRaise(ref _count, value); | |
} | |
public GroupTansformed(IGroup<Male, int, Greek> group) | |
{ | |
Key = group.Key; | |
//Need to raise a notify property changed event for the count property. | |
//NB: Also change binding to <TextBlock Text="{Binding Count}" /> | |
_cleanUp = group.Cache.CountChanged.Subscribe(c => Count = c); } | |
public void Dispose() | |
{ | |
_cleanUp.Dispose(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment