ListObserver.cs 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Text;
  4. namespace UniRx.InternalUtil
  5. {
  6. public class ListObserver<T> : IObserver<T>
  7. {
  8. private readonly ImmutableList<IObserver<T>> _observers;
  9. public ListObserver(ImmutableList<IObserver<T>> observers)
  10. {
  11. _observers = observers;
  12. }
  13. public void OnCompleted()
  14. {
  15. var targetObservers = _observers.Data;
  16. for (int i = 0; i < targetObservers.Length; i++)
  17. {
  18. targetObservers[i].OnCompleted();
  19. }
  20. }
  21. public void OnError(Exception error)
  22. {
  23. var targetObservers = _observers.Data;
  24. for (int i = 0; i < targetObservers.Length; i++)
  25. {
  26. targetObservers[i].OnError(error);
  27. }
  28. }
  29. public void OnNext(T value)
  30. {
  31. var targetObservers = _observers.Data;
  32. for (int i = 0; i < targetObservers.Length; i++)
  33. {
  34. targetObservers[i].OnNext(value);
  35. }
  36. }
  37. internal IObserver<T> Add(IObserver<T> observer)
  38. {
  39. return new ListObserver<T>(_observers.Add(observer));
  40. }
  41. internal IObserver<T> Remove(IObserver<T> observer)
  42. {
  43. var i = Array.IndexOf(_observers.Data, observer);
  44. if (i < 0)
  45. return this;
  46. if (_observers.Data.Length == 2)
  47. {
  48. return _observers.Data[1 - i];
  49. }
  50. else
  51. {
  52. return new ListObserver<T>(_observers.Remove(observer));
  53. }
  54. }
  55. }
  56. public class EmptyObserver<T> : IObserver<T>
  57. {
  58. public static readonly EmptyObserver<T> Instance = new EmptyObserver<T>();
  59. EmptyObserver()
  60. {
  61. }
  62. public void OnCompleted()
  63. {
  64. }
  65. public void OnError(Exception error)
  66. {
  67. }
  68. public void OnNext(T value)
  69. {
  70. }
  71. }
  72. public class ThrowObserver<T> : IObserver<T>
  73. {
  74. public static readonly ThrowObserver<T> Instance = new ThrowObserver<T>();
  75. ThrowObserver()
  76. {
  77. }
  78. public void OnCompleted()
  79. {
  80. }
  81. public void OnError(Exception error)
  82. {
  83. error.Throw();
  84. }
  85. public void OnNext(T value)
  86. {
  87. }
  88. }
  89. public class DisposedObserver<T> : IObserver<T>
  90. {
  91. public static readonly DisposedObserver<T> Instance = new DisposedObserver<T>();
  92. DisposedObserver()
  93. {
  94. }
  95. public void OnCompleted()
  96. {
  97. throw new ObjectDisposedException("");
  98. }
  99. public void OnError(Exception error)
  100. {
  101. throw new ObjectDisposedException("");
  102. }
  103. public void OnNext(T value)
  104. {
  105. throw new ObjectDisposedException("");
  106. }
  107. }
  108. }