Skip to content

Instantly share code, notes, and snippets.

@JohanLarsson
Last active August 29, 2015 13:59
Show Gist options
  • Save JohanLarsson/10497547 to your computer and use it in GitHub Desktop.
Save JohanLarsson/10497547 to your computer and use it in GitHub Desktop.
public class History<T> : IEnumerable<HistoryItem<T>>, INotifyCollectionChanged
{
private readonly ConcurrentStack<HistoryItem<T>> _stack = new ConcurrentStack<HistoryItem<T>>();
public void Push(T item)
{
_stack.Push(new HistoryItem<T>(item));
OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Add, item));
}
public IEnumerator<HistoryItem<T>> GetEnumerator()
{
return _stack.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
public event NotifyCollectionChangedEventHandler CollectionChanged;
protected virtual void OnCollectionChanged(NotifyCollectionChangedEventArgs e)
{
NotifyCollectionChangedEventHandler handler = CollectionChanged;
if (handler != null)
{
if (Application.Current != null && Application.Current.Dispatcher != null)
{
Application.Current.Dispatcher.BeginInvoke(new Action(() => handler(this, e)));
}
else
{
handler(this, e);
}
}
}
}
public class HistoryItem<T>
{
public HistoryItem(T value)
{
Timestamp = DateTime.UtcNow;
Value = value;
}
public DateTime Timestamp { get; private set; }
public T Value { get; private set; }
}
public class ObservingHistory<T> : History<T>, IDisposable
{
private IDisposable _subscription;
public ObservingHistory(IObservable<T> observable)
{
_subscription = observable.Subscribe(Push);
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
if (_subscription != null)
{
_subscription.Dispose();
_subscription = null;
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment