ColdObservable.cs 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  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 ColdObservable<T> : ITestableObservable<T>
  11. {
  12. readonly TestScheduler scheduler;
  13. readonly Recorded<Notification<T>>[] messages;
  14. readonly List<Subscription> subscriptions = new List<Subscription>();
  15. public ColdObservable(TestScheduler scheduler, params Recorded<Notification<T>>[] messages)
  16. {
  17. if (scheduler == null)
  18. throw new ArgumentNullException(nameof(scheduler));
  19. if (messages == null)
  20. throw new ArgumentNullException(nameof(messages));
  21. this.scheduler = scheduler;
  22. this.messages = messages;
  23. }
  24. public virtual IDisposable Subscribe(IObserver<T> observer)
  25. {
  26. if (observer == null)
  27. throw new ArgumentNullException(nameof(observer));
  28. subscriptions.Add(new Subscription(scheduler.Clock));
  29. var index = subscriptions.Count - 1;
  30. var d = new CompositeDisposable();
  31. for (var i = 0; i < messages.Length; ++i)
  32. {
  33. var notification = messages[i].Value;
  34. d.Add(scheduler.ScheduleRelative(default(object), messages[i].Time, (scheduler1, state1) => { notification.Accept(observer); return Disposable.Empty; }));
  35. }
  36. return Disposable.Create(() =>
  37. {
  38. subscriptions[index] = new Subscription(subscriptions[index].Subscribe, scheduler.Clock);
  39. d.Dispose();
  40. });
  41. }
  42. public IList<Subscription> Subscriptions
  43. {
  44. get { return subscriptions; }
  45. }
  46. public IList<Recorded<Notification<T>>> Messages
  47. {
  48. get { return messages; }
  49. }
  50. }
  51. }