Sample05_ConvertFromCoroutine.cs 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. using System;
  2. using System.Collections;
  3. using System.Threading;
  4. using UnityEngine;
  5. #if UNITY_2018_3_OR_NEWER
  6. #pragma warning disable CS0618
  7. #endif
  8. namespace UniRx.Examples
  9. {
  10. public class Sample05_ConvertFromCoroutine
  11. {
  12. // public method
  13. public static IObservable<string> GetWWW(string url)
  14. {
  15. // convert coroutine to IObservable
  16. return Observable.FromCoroutine<string>((observer, cancellationToken) => GetWWWCore(url, observer, cancellationToken));
  17. }
  18. // IEnumerator with callback
  19. static IEnumerator GetWWWCore(string url, IObserver<string> observer, CancellationToken cancellationToken)
  20. {
  21. var www = new UnityEngine.WWW(url);
  22. while (!www.isDone && !cancellationToken.IsCancellationRequested)
  23. {
  24. yield return null;
  25. }
  26. if (cancellationToken.IsCancellationRequested) yield break;
  27. if (www.error != null)
  28. {
  29. observer.OnError(new Exception(www.error));
  30. }
  31. else
  32. {
  33. observer.OnNext(www.text);
  34. observer.OnCompleted();
  35. }
  36. }
  37. }
  38. }
  39. #if UNITY_2018_3_OR_NEWER
  40. #pragma warning restore CS0618
  41. #endif