ObservableExtensions.cs 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. using System;
  2. using System.Collections.Generic;
  3. namespace Jint.Tests.Runtime.ExtensionMethods
  4. {
  5. internal class Subscribe<T> : IObserver<T>
  6. {
  7. private readonly Action<T> onNext;
  8. private readonly Action<Exception> onError;
  9. private readonly Action onCompleted;
  10. int isStopped = 0;
  11. public Subscribe(Action<T> onNext, Action<Exception> onError, Action onCompleted)
  12. {
  13. this.onNext = onNext;
  14. this.onError = onError;
  15. this.onCompleted = onCompleted;
  16. }
  17. public void OnNext(T value)
  18. {
  19. if (isStopped == 0)
  20. {
  21. onNext(value);
  22. }
  23. }
  24. public void OnError(Exception error)
  25. {
  26. onError(error);
  27. }
  28. public void OnCompleted()
  29. {
  30. onCompleted();
  31. }
  32. }
  33. public static partial class ObservableExtensions
  34. {
  35. public static void Subscribe<T>(this IObservable<T> source, Action<T> onNext)
  36. {
  37. var subs = new Subscribe<T>(onNext, null, null);
  38. source.Subscribe(subs);
  39. }
  40. }
  41. public class NameObservable : IObservable<string>
  42. {
  43. private List<IObserver<string>> observers = new List<IObserver<string>>();
  44. public string Last { get; private set; }
  45. public IDisposable Subscribe(IObserver<string> observer)
  46. {
  47. if (!observers.Contains(observer))
  48. observers.Add(observer);
  49. return new Unsubscriber(observers, observer);
  50. }
  51. private class Unsubscriber : IDisposable
  52. {
  53. private List<IObserver<string>> _observers;
  54. private IObserver<string> _observer;
  55. public Unsubscriber(List<IObserver<string>> observers, IObserver<string> observer)
  56. {
  57. this._observers = observers;
  58. this._observer = observer;
  59. }
  60. public void Dispose()
  61. {
  62. if (_observer != null && _observers.Contains(_observer))
  63. _observers.Remove(_observer);
  64. }
  65. }
  66. public void UpdateName(string name)
  67. {
  68. Last = name;
  69. foreach (var observer in observers)
  70. {
  71. observer.OnNext(name);
  72. }
  73. }
  74. public void CommitName()
  75. {
  76. foreach (var observer in observers.ToArray())
  77. {
  78. observer.OnCompleted();
  79. }
  80. observers.Clear();
  81. }
  82. }
  83. }