TestSubject.cs 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. // Copyright (c) The Avalonia Project. All rights reserved.
  2. // Licensed under the MIT license. See licence.md file in the project root for full license information.
  3. using System;
  4. using System.Collections.Generic;
  5. using System.Reactive.Disposables;
  6. namespace Avalonia.Styling.UnitTests
  7. {
  8. internal class TestSubject<T> : IObserver<T>, IObservable<T>
  9. {
  10. private readonly T _initial;
  11. private readonly List<IObserver<T>> _subscribers = new List<IObserver<T>>();
  12. public TestSubject(T initial)
  13. {
  14. _initial = initial;
  15. }
  16. public int SubscriberCount => _subscribers.Count;
  17. public void OnCompleted()
  18. {
  19. foreach (IObserver<T> subscriber in _subscribers.ToArray())
  20. {
  21. subscriber.OnCompleted();
  22. }
  23. }
  24. public void OnError(Exception error)
  25. {
  26. foreach (IObserver<T> subscriber in _subscribers.ToArray())
  27. {
  28. subscriber.OnError(error);
  29. }
  30. }
  31. public void OnNext(T value)
  32. {
  33. foreach (IObserver<T> subscriber in _subscribers.ToArray())
  34. {
  35. subscriber.OnNext(value);
  36. }
  37. }
  38. public IDisposable Subscribe(IObserver<T> observer)
  39. {
  40. _subscribers.Add(observer);
  41. observer.OnNext(_initial);
  42. return Disposable.Create(() => _subscribers.Remove(observer));
  43. }
  44. }
  45. }