Guest User

Untitled

a guest
Feb 11th, 2019
113
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.31 KB | None | 0 0
  1. /// <summary>
  2. /// Subscribes collection child item events to some specific handler.
  3. /// The logic of subscription and unsubscription can be complicated,
  4. /// considering that you need to take into account collection changes,
  5. /// new child items have to subscribe, while unused and removed items
  6. /// need to unsubscribe.
  7. /// </summary>
  8. public class CollectionSubscription<TItem, THandler>
  9. {
  10. private Action<TItem> subscribe;
  11. private Action<TItem> unsubscribe;
  12. private Action raiseEvent;
  13.  
  14. public CollectionSubscription(Action<TItem> subscribe, Action<TItem> unsubscribe, Action raiseEvent)
  15. {
  16. this.subscribe = subscribe;
  17. this.unsubscribe = unsubscribe;
  18. this.raiseEvent = raiseEvent;
  19. }
  20.  
  21. public void Subscribe(ObservableCollection<TItem> collection)
  22. {
  23. collection.CollectionChanged -= OnCollectionChanged;
  24. collection.CollectionChanged += OnCollectionChanged;
  25. foreach (var item in collection)
  26. {
  27. unsubscribe(item);
  28. subscribe(item);
  29. }
  30. }
  31.  
  32. public void Unsubscribe(ObservableCollection<TItem> collection)
  33. {
  34. collection.CollectionChanged -= OnCollectionChanged;
  35. foreach (var item in collection)
  36. unsubscribe(item);
  37. }
  38.  
  39. private void OnCollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
  40. {
  41. if (e.Action == NotifyCollectionChangedAction.Reset)
  42. {
  43. var collection = sender as IEnumerable<TItem>;
  44. foreach (var item in collection)
  45. {
  46. unsubscribe(item);
  47. subscribe(item);
  48. }
  49. }
  50.  
  51. var oldItems = e.OldItems as IEnumerable<TItem>;
  52. if (oldItems != null)
  53. {
  54. foreach (var oldItem in oldItems)
  55. unsubscribe(oldItem);
  56. }
  57.  
  58. var newItems = e.NewItems as IEnumerable<TItem>;
  59. if (newItems != null)
  60. {
  61. foreach (var newItem in newItems)
  62. {
  63. unsubscribe(newItem);
  64. subscribe(newItem);
  65. }
  66. }
  67.  
  68. raiseEvent();
  69. }
  70. }
Add Comment
Please, Sign In to add comment