1
0

ScheduledNotifier.cs 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. using System;
  2. namespace UniRx
  3. {
  4. /// <summary>
  5. /// Notify value on setuped scheduler.
  6. /// </summary>
  7. public class ScheduledNotifier<T> : IObservable<T>, IProgress<T>
  8. {
  9. readonly IScheduler scheduler;
  10. readonly Subject<T> trigger = new Subject<T>();
  11. /// <summary>
  12. /// Use scheduler is Scheduler.DefaultSchedulers.ConstantTimeOperations.
  13. /// </summary>
  14. public ScheduledNotifier()
  15. {
  16. this.scheduler = Scheduler.DefaultSchedulers.ConstantTimeOperations;
  17. }
  18. /// <summary>
  19. /// Use scheduler is argument's scheduler.
  20. /// </summary>
  21. public ScheduledNotifier(IScheduler scheduler)
  22. {
  23. if (scheduler == null)
  24. {
  25. throw new ArgumentNullException("scheduler");
  26. }
  27. this.scheduler = scheduler;
  28. }
  29. /// <summary>
  30. /// Push value to subscribers on setuped scheduler.
  31. /// </summary>
  32. public void Report(T value)
  33. {
  34. scheduler.Schedule(() => trigger.OnNext(value));
  35. }
  36. /// <summary>
  37. /// Push value to subscribers on setuped scheduler.
  38. /// </summary>
  39. public IDisposable Report(T value, TimeSpan dueTime)
  40. {
  41. var cancel = scheduler.Schedule(dueTime, () => trigger.OnNext(value));
  42. return cancel;
  43. }
  44. /// <summary>
  45. /// Push value to subscribers on setuped scheduler.
  46. /// </summary>
  47. public IDisposable Report(T value, DateTimeOffset dueTime)
  48. {
  49. var cancel = scheduler.Schedule(dueTime, () => trigger.OnNext(value));
  50. return cancel;
  51. }
  52. /// <summary>
  53. /// Subscribe observer.
  54. /// </summary>
  55. public IDisposable Subscribe(IObserver<T> observer)
  56. {
  57. if (observer == null)
  58. {
  59. throw new ArgumentNullException("observer");
  60. }
  61. return trigger.Subscribe(observer);
  62. }
  63. }
  64. }