Sample10_MainThreadDispatcher.cs 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. using System;
  2. using System.Collections;
  3. using UnityEngine;
  4. namespace UniRx.Examples
  5. {
  6. public class Sample10_MainThreadDispatcher
  7. {
  8. public void Run()
  9. {
  10. // MainThreadDispatcher is heart of Rx and Unity integration
  11. // StartCoroutine can start coroutine besides MonoBehaviour.
  12. MainThreadDispatcher.StartCoroutine(TestAsync());
  13. // We have two way of run coroutine, FromCoroutine or StartCoroutine.
  14. // StartCoroutine is Unity primitive way and it's awaitable by yield return.
  15. // FromCoroutine is Rx, it's composable and cancellable by subscription's IDisposable.
  16. // FromCoroutine's overload can have return value, see:Sample05_ConvertFromCoroutine
  17. Observable.FromCoroutine(TestAsync).Subscribe();
  18. // Add Action to MainThreadDispatcher. Action is saved queue, run on next update.
  19. MainThreadDispatcher.Post(_ => Debug.Log("test"), null);
  20. // Timebased operations is run on MainThread(as default)
  21. // All timebased operation(Interval, Timer, Delay, Buffer, etc...)is single thread, thread safe!
  22. Observable.Interval(TimeSpan.FromSeconds(1))
  23. .Subscribe(x => Debug.Log(x));
  24. // Observable.Start use ThreadPool Scheduler as default.
  25. // ObserveOnMainThread return to mainthread
  26. Observable.Start(() => Unit.Default) // asynchronous work
  27. .ObserveOnMainThread()
  28. .Subscribe(x => Debug.Log(x));
  29. }
  30. IEnumerator TestAsync()
  31. {
  32. Debug.Log("a");
  33. yield return new WaitForSeconds(1);
  34. Debug.Log("b");
  35. yield return new WaitForSeconds(1);
  36. Debug.Log("c");
  37. yield return new WaitForSeconds(1);
  38. Debug.Log("d");
  39. }
  40. }
  41. }