Skip to content

Instantly share code, notes, and snippets.

@hacklex
Created November 2, 2022 06:36
Show Gist options
  • Select an option

  • Save hacklex/9a5d8975afd3f1a69b0e3d21331b6b66 to your computer and use it in GitHub Desktop.

Select an option

Save hacklex/9a5d8975afd3f1a69b0e3d21331b6b66 to your computer and use it in GitHub Desktop.
Transaction-aware collection support for PhoneWave
public class PhoneWaveCollectionChangeAggregator<T> : TransactionChange
{
List<(bool isRemove, int index, T item)> _changes = new();
ObservableCollection<T> _target;
public PhoneWaveCollectionChangeAggregator(ObservableCollection<T> target)
{
_target = target;
}
public void AddItem(T item, int index) => _changes.Add((false, index, item));
public void RemoveItem(T item, int index) => _changes.Add((true, index, item));
public override void Rollback()
{
foreach(var change in Enumerable.Reverse(_changes))
{
if (change.isRemove) _target.Insert(change.index, change.item);
else _target.RemoveAt(change.index);
}
}
public override void RollForward()
{
foreach (var change in _changes)
{
if (!change.isRemove) _target.Insert(change.index, change.item);
else _target.RemoveAt(change.index);
}
}
}
public class PhoneWaveCollection<T> : ObservableCollection<T>
{
public PhoneWaveContext Context { get; }
public PhoneWaveCollection(PhoneWaveContext context)
{
Context = context;
}
protected override void ClearItems()
{
for (int i = Count - 1; i >= 0; i--)
{
Context.UpdateCollection(this, true, i, this[i]);
}
base.ClearItems();
}
protected override void InsertItem(int index, T item)
{
Context.UpdateCollection(this, false, index, item);
base.InsertItem(index, item);
}
protected override void MoveItem(int oldIndex, int newIndex)
{
var item = this[oldIndex];
Context.UpdateCollection(this, true, oldIndex, item);
Context.UpdateCollection(this, false, newIndex, item);
base.MoveItem(oldIndex, newIndex);
}
protected override void RemoveItem(int index)
{
Context.UpdateCollection(this, true, index, this[index]);
base.RemoveItem(index);
}
protected override void SetItem(int index, T item)
{
Context.UpdateCollection(this, true, index, this[index]);
Context.UpdateCollection(this, false, index, item);
base.SetItem(index, item);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment