FrameTimeInterval.cs 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. using System;
  2. namespace UniRx.Operators
  3. {
  4. internal class FrameTimeIntervalObservable<T> : OperatorObservableBase<UniRx.TimeInterval<T>>
  5. {
  6. readonly IObservable<T> source;
  7. readonly bool ignoreTimeScale;
  8. public FrameTimeIntervalObservable(IObservable<T> source, bool ignoreTimeScale)
  9. : base(source.IsRequiredSubscribeOnCurrentThread())
  10. {
  11. this.source = source;
  12. this.ignoreTimeScale = ignoreTimeScale;
  13. }
  14. protected override IDisposable SubscribeCore(IObserver<UniRx.TimeInterval<T>> observer, IDisposable cancel)
  15. {
  16. return source.Subscribe(new FrameTimeInterval(this, observer, cancel));
  17. }
  18. class FrameTimeInterval : OperatorObserverBase<T, UniRx.TimeInterval<T>>
  19. {
  20. readonly FrameTimeIntervalObservable<T> parent;
  21. float lastTime;
  22. public FrameTimeInterval(FrameTimeIntervalObservable<T> parent, IObserver<UniRx.TimeInterval<T>> observer, IDisposable cancel)
  23. : base(observer, cancel)
  24. {
  25. this.parent = parent;
  26. this.lastTime = (parent.ignoreTimeScale)
  27. ? UnityEngine.Time.unscaledTime
  28. : UnityEngine.Time.time;
  29. }
  30. public override void OnNext(T value)
  31. {
  32. var now = (parent.ignoreTimeScale)
  33. ? UnityEngine.Time.unscaledTime
  34. : UnityEngine.Time.time;
  35. var span = now - lastTime;
  36. lastTime = now;
  37. base.observer.OnNext(new UniRx.TimeInterval<T>(value, TimeSpan.FromSeconds(span)));
  38. }
  39. public override void OnError(Exception error)
  40. {
  41. try { observer.OnError(error); }
  42. finally { Dispose(); }
  43. }
  44. public override void OnCompleted()
  45. {
  46. try { observer.OnCompleted(); }
  47. finally { Dispose(); }
  48. }
  49. }
  50. }
  51. }