HotObservable.cs 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. // Licensed to the .NET Foundation under one or more agreements.
  2. // The .NET Foundation licenses this file to you under the Apache 2.0 License.
  3. // See the LICENSE file in the project root for more information.
  4. using System.Collections.Generic;
  5. using System.Reactive;
  6. using System;
  7. using System.Reactive.Disposables;
  8. namespace Microsoft.Reactive.Testing
  9. {
  10. class HotObservable<T> : ITestableObservable<T>
  11. {
  12. readonly TestScheduler scheduler;
  13. readonly List<IObserver<T>> observers = new List<IObserver<T>>();
  14. readonly List<Subscription> subscriptions = new List<Subscription>();
  15. readonly Recorded<Notification<T>>[] messages;
  16. public HotObservable(TestScheduler scheduler, params Recorded<Notification<T>>[] messages)
  17. {
  18. if (scheduler == null)
  19. throw new ArgumentNullException("scheduler");
  20. if (messages == null)
  21. throw new ArgumentNullException("messages");
  22. this.scheduler = scheduler;
  23. this.messages = messages;
  24. for (var i = 0; i < messages.Length; ++i)
  25. {
  26. var notification = messages[i].Value;
  27. scheduler.ScheduleAbsolute(default(object), messages[i].Time, (scheduler1, state1) =>
  28. {
  29. var _observers = observers.ToArray();
  30. for (var j = 0; j < _observers.Length; ++j)
  31. {
  32. notification.Accept(_observers[j]);
  33. }
  34. return Disposable.Empty;
  35. });
  36. }
  37. }
  38. public virtual IDisposable Subscribe(IObserver<T> observer)
  39. {
  40. if (observer == null)
  41. throw new ArgumentNullException("observer");
  42. observers.Add(observer);
  43. subscriptions.Add(new Subscription(scheduler.Clock));
  44. var index = subscriptions.Count - 1;
  45. return Disposable.Create(() =>
  46. {
  47. observers.Remove(observer);
  48. subscriptions[index] = new Subscription(subscriptions[index].Subscribe, scheduler.Clock);
  49. });
  50. }
  51. public IList<Subscription> Subscriptions
  52. {
  53. get { return subscriptions; }
  54. }
  55. public IList<Recorded<Notification<T>>> Messages
  56. {
  57. get { return messages; }
  58. }
  59. }
  60. }