Last active
May 18, 2016 14:58
-
-
Save mcintyre321/147b1ae9856afbd1b20b0fa78cd7a9f7 to your computer and use it in GitHub Desktop.
Simple Event Sourcing using NMF
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
void Main() | |
{ | |
var events = new ObservableCollection<Event>(); | |
var state = new NotifyCollection<object>(); | |
events.OnAdd(next => | |
{ | |
if (next is UserWasAdded) | |
{ | |
var userWasAdded = (UserWasAdded)next; | |
state.Add(new User() { UserName = userWasAdded.UserName }); | |
} | |
if (next is UserWasDeleted) | |
{ | |
var userWasDeleted = (UserWasDeleted)next; | |
var user = state.OfType<User>().Single(u => u.UserName == userWasDeleted.UserName); | |
user.Deleted = true; | |
} | |
}); | |
var activeUsers = state.WithUpdates().OfType<User>().Where(u => u.Deleted == false); | |
("Active users: " + activeUsers.Count()).Dump(); | |
events.Add(new UserWasAdded() { UserName = "Harry" }); | |
("Active users: " + activeUsers.Count()).Dump(); | |
events.Add(new UserWasDeleted() { UserName = "Harry" }); | |
("Active users: " + activeUsers.Count()).Dump(); | |
} | |
class Event { } | |
class UserWasAdded : Event { public string UserName { get; set; } } | |
class UserWasDeleted : Event { public string UserName { get; set; } } | |
class User : INotifyPropertyChanged { | |
public string UserName { get; set; } | |
bool _deleted; | |
public bool Deleted | |
{ | |
get { return _deleted; } set{ _deleted = value; OnPropertyChanged();} | |
} | |
public event PropertyChangedEventHandler PropertyChanged; | |
protected void OnPropertyChanged([CallerMemberName] string propertyName = null) | |
{ | |
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@bwanner Am I using this incorrectly? I get
InvalidOperationException: Sequence contains no elements
on line 6edit: ah you need to provide a seed to Aggregate if the collection is empty.