Sample01_ObservableWWW.cs 3.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. #if !(UNITY_METRO || UNITY_WP8)
  2. #if UNITY_2018_3_OR_NEWER
  3. #pragma warning disable CS0618
  4. #endif
  5. using UnityEngine;
  6. namespace UniRx.Examples
  7. {
  8. // sample script, attach your object.
  9. public class Sample01_ObservableWWW : MonoBehaviour
  10. {
  11. void Start()
  12. {
  13. // Basic: Download from google.
  14. {
  15. ObservableWWW.Get("http://google.co.jp/")
  16. .Subscribe(
  17. x => Debug.Log(x.Substring(0, 100)), // onSuccess
  18. ex => Debug.LogException(ex)); // onError
  19. }
  20. // Linear Pattern with LINQ Query Expressions
  21. // download after google, start bing download
  22. {
  23. var query = from google in ObservableWWW.Get("http://google.com/")
  24. from bing in ObservableWWW.Get("http://bing.com/")
  25. select new { google, bing };
  26. var cancel = query.Subscribe(x => Debug.Log(x.google.Substring(0, 100) + ":" + x.bing.Substring(0, 100)));
  27. // Call Dispose is cancel downloading.
  28. cancel.Dispose();
  29. }
  30. // Observable.WhenAll is for parallel asynchronous operation
  31. // (It's like Observable.Zip but specialized for single async operations like Task.WhenAll of .NET 4)
  32. {
  33. var parallel = Observable.WhenAll(
  34. ObservableWWW.Get("http://google.com/"),
  35. ObservableWWW.Get("http://bing.com/"),
  36. ObservableWWW.Get("http://unity3d.com/"));
  37. parallel.Subscribe(xs =>
  38. {
  39. Debug.Log(xs[0].Substring(0, 100)); // google
  40. Debug.Log(xs[1].Substring(0, 100)); // bing
  41. Debug.Log(xs[2].Substring(0, 100)); // unity
  42. });
  43. }
  44. // with Progress
  45. {
  46. // notifier for progress
  47. var progressNotifier = new ScheduledNotifier<float>();
  48. progressNotifier.Subscribe(x => Debug.Log(x)); // write www.progress
  49. // pass notifier to WWW.Get/Post
  50. ObservableWWW.Get("http://google.com/", progress: progressNotifier).Subscribe();
  51. }
  52. // with Error
  53. {
  54. // If WWW has .error, ObservableWWW throws WWWErrorException to onError pipeline.
  55. // WWWErrorException has RawErrorMessage, HasResponse, StatusCode, ResponseHeaders
  56. ObservableWWW.Get("http://www.google.com/404")
  57. .CatchIgnore((WWWErrorException ex) =>
  58. {
  59. Debug.Log(ex.RawErrorMessage);
  60. if (ex.HasResponse)
  61. {
  62. Debug.Log(ex.StatusCode);
  63. }
  64. foreach (var item in ex.ResponseHeaders)
  65. {
  66. Debug.Log(item.Key + ":" + item.Value);
  67. }
  68. })
  69. .Subscribe();
  70. }
  71. }
  72. }
  73. }
  74. #endif
  75. #if UNITY_2018_3_OR_NEWER
  76. #pragma warning restore CS0618
  77. #endif