Skip to content

Instantly share code, notes, and snippets.

@RolandPheasant
Last active January 10, 2022 09:09
Show Gist options
  • Save RolandPheasant/6e50c0341c4bf8db202f24b616491306 to your computer and use it in GitHub Desktop.
Save RolandPheasant/6e50c0341c4bf8db202f24b616491306 to your computer and use it in GitHub Desktop.
using System;
using DynamicData.Cache.Internal;
namespace DynamicData.Binding
{
public class MyObservableCollectionAdaptor<TObject, TKey> : IObservableCollectionAdaptor<TObject, TKey>
where TKey : notnull
{
private readonly Cache<TObject, TKey> _cache = new();
private readonly int _refreshThreshold;
private bool _loaded;
public MyObservableCollectionAdaptor(int refreshThreshold = 25) => _refreshThreshold = refreshThreshold;
public void Adapt(IChangeSet<TObject, TKey> changes, IObservableCollection<TObject> collection)
{
if (changes is null)
{
throw new ArgumentNullException(nameof(changes));
}
if (collection is null)
{
throw new ArgumentNullException(nameof(collection));
}
_cache.Clone(changes);
if (changes.Count - changes.Refreshes > _refreshThreshold || !_loaded)
{
_loaded = true;
using (collection.SuspendNotifications())
{
collection.Load(_cache.Items);
}
}
else
{
using (collection.SuspendCount())
{
DoUpdate(changes, collection);
}
}
}
private static void DoUpdate(IChangeSet<TObject, TKey> updates, IObservableCollection<TObject> list)
{
foreach (var update in updates)
{
switch (update.Reason)
{
case ChangeReason.Add:
list.Add(update.Current);
break;
case ChangeReason.Remove:
list.Remove(update.Current);
break;
//This was changed in a PR 1 year ago and my be the problem.
case ChangeReason.Update:
list.Replace(update.Previous.Value, update.Current);
break;
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment