2
0

AsyncOperationExtensions.cs 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. using System;
  2. using System.Collections;
  3. using System.Threading;
  4. using UnityEngine;
  5. #if !UniRxLibrary
  6. using ObservableUnity = UniRx.Observable;
  7. #endif
  8. namespace UniRx
  9. {
  10. public static partial class AsyncOperationExtensions
  11. {
  12. /// <summary>
  13. /// If you needs return value, use AsAsyncOperationObservable instead.
  14. /// </summary>
  15. public static IObservable<AsyncOperation> AsObservable(this AsyncOperation asyncOperation, IProgress<float> progress = null)
  16. {
  17. return ObservableUnity.FromCoroutine<AsyncOperation>((observer, cancellation) => AsObservableCore(asyncOperation, observer, progress, cancellation));
  18. }
  19. // T: where T : AsyncOperation is ambigious with IObservable<T>.AsObservable
  20. public static IObservable<T> AsAsyncOperationObservable<T>(this T asyncOperation, IProgress<float> progress = null)
  21. where T : AsyncOperation
  22. {
  23. return ObservableUnity.FromCoroutine<T>((observer, cancellation) => AsObservableCore(asyncOperation, observer, progress, cancellation));
  24. }
  25. static IEnumerator AsObservableCore<T>(T asyncOperation, IObserver<T> observer, IProgress<float> reportProgress, CancellationToken cancel)
  26. where T : AsyncOperation
  27. {
  28. if (reportProgress != null)
  29. {
  30. while (!asyncOperation.isDone && !cancel.IsCancellationRequested)
  31. {
  32. try
  33. {
  34. reportProgress.Report(asyncOperation.progress);
  35. }
  36. catch (Exception ex)
  37. {
  38. observer.OnError(ex);
  39. yield break;
  40. }
  41. yield return null;
  42. }
  43. }
  44. else
  45. {
  46. if (!asyncOperation.isDone)
  47. {
  48. yield return asyncOperation;
  49. }
  50. }
  51. if (cancel.IsCancellationRequested) yield break;
  52. if (reportProgress != null)
  53. {
  54. try
  55. {
  56. reportProgress.Report(asyncOperation.progress);
  57. }
  58. catch (Exception ex)
  59. {
  60. observer.OnError(ex);
  61. yield break;
  62. }
  63. }
  64. observer.OnNext(asyncOperation);
  65. observer.OnCompleted();
  66. }
  67. }
  68. }