MySubject.cs 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. // Licensed to the .NET Foundation under one or more agreements.
  2. // The .NET Foundation licenses this file to you under the MIT License.
  3. // See the LICENSE file in the project root for more information.
  4. using System;
  5. using System.Collections.Generic;
  6. using System.Reactive.Disposables;
  7. using System.Reactive.Subjects;
  8. namespace ReactiveTests.Tests
  9. {
  10. internal class MySubject : ISubject<int>
  11. {
  12. private readonly Dictionary<int, IDisposable> _disposeOn = [];
  13. public void DisposeOn(int value, IDisposable disposable)
  14. {
  15. _disposeOn[value] = disposable;
  16. }
  17. private readonly List<IObserver<int>> _observers = new();
  18. public void OnNext(int value)
  19. {
  20. foreach (var observer in _observers.ToArray())
  21. {
  22. observer.OnNext(value);
  23. }
  24. if (_disposeOn.TryGetValue(value, out var disconnect))
  25. {
  26. disconnect.Dispose();
  27. }
  28. }
  29. public void OnError(Exception exception)
  30. {
  31. foreach (var observer in _observers.ToArray())
  32. {
  33. observer.OnError(exception);
  34. }
  35. }
  36. public void OnCompleted()
  37. {
  38. foreach (var observer in _observers.ToArray())
  39. {
  40. observer.OnCompleted();
  41. }
  42. }
  43. public IDisposable Subscribe(IObserver<int> observer)
  44. {
  45. _subscribeCount++;
  46. _observers.Add(observer);
  47. return Disposable.Create(() =>
  48. {
  49. _observers.Remove(observer);
  50. _disposed = true;
  51. });
  52. }
  53. private int _subscribeCount;
  54. private bool _disposed;
  55. public int SubscribeCount { get { return _subscribeCount; } }
  56. public bool Disposed { get { return _disposed; } }
  57. }
  58. }