Progress.cs 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. using System;
  2. using System.Collections.Generic;
  3. using Cysharp.Threading.Tasks.Internal;
  4. namespace Cysharp.Threading.Tasks
  5. {
  6. /// <summary>
  7. /// Lightweight IProgress[T] factory.
  8. /// </summary>
  9. public static class Progress
  10. {
  11. public static IProgress<T> Create<T>(Action<T> handler)
  12. {
  13. if (handler == null) return NullProgress<T>.Instance;
  14. return new AnonymousProgress<T>(handler);
  15. }
  16. public static IProgress<T> CreateOnlyValueChanged<T>(Action<T> handler, IEqualityComparer<T> comparer = null)
  17. {
  18. if (handler == null) return NullProgress<T>.Instance;
  19. #if UNITY_2018_3_OR_NEWER
  20. return new OnlyValueChangedProgress<T>(handler, comparer ?? UnityEqualityComparer.GetDefault<T>());
  21. #else
  22. return new OnlyValueChangedProgress<T>(handler, comparer ?? EqualityComparer<T>.Default);
  23. #endif
  24. }
  25. sealed class NullProgress<T> : IProgress<T>
  26. {
  27. public static readonly IProgress<T> Instance = new NullProgress<T>();
  28. NullProgress()
  29. {
  30. }
  31. public void Report(T value)
  32. {
  33. }
  34. }
  35. sealed class AnonymousProgress<T> : IProgress<T>
  36. {
  37. readonly Action<T> action;
  38. public AnonymousProgress(Action<T> action)
  39. {
  40. this.action = action;
  41. }
  42. public void Report(T value)
  43. {
  44. action(value);
  45. }
  46. }
  47. sealed class OnlyValueChangedProgress<T> : IProgress<T>
  48. {
  49. readonly Action<T> action;
  50. readonly IEqualityComparer<T> comparer;
  51. bool isFirstCall;
  52. T latestValue;
  53. public OnlyValueChangedProgress(Action<T> action, IEqualityComparer<T> comparer)
  54. {
  55. this.action = action;
  56. this.comparer = comparer;
  57. this.isFirstCall = true;
  58. }
  59. public void Report(T value)
  60. {
  61. if (isFirstCall)
  62. {
  63. isFirstCall = false;
  64. }
  65. else if (comparer.Equals(value, latestValue))
  66. {
  67. return;
  68. }
  69. latestValue = value;
  70. action(value);
  71. }
  72. }
  73. }
  74. }