Sample09_EventHandling.cs 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. #pragma warning disable 0067
  2. using System;
  3. using UnityEngine;
  4. namespace UniRx.Examples
  5. {
  6. public class Sample09_EventHandling : MonoBehaviour
  7. {
  8. public class MyEventArgs : EventArgs
  9. {
  10. public int MyProperty { get; set; }
  11. }
  12. public event EventHandler<MyEventArgs> FooBar;
  13. public event Action<int> FooFoo;
  14. CompositeDisposable disposables = new CompositeDisposable();
  15. // Subject is Rx's native event expression and recommend way for use Rx as event.
  16. // Subject.OnNext as fire event,
  17. // expose IObserver is subscibable for external source, it's no need convert.
  18. Subject<int> onBarBar = new Subject<int>();
  19. public IObservable<int> OnBarBar { get { return onBarBar; } }
  20. void Start()
  21. {
  22. // convert to IO<EventPattern> as (sender, eventArgs)
  23. Observable.FromEventPattern<EventHandler<MyEventArgs>, MyEventArgs>(
  24. h => h.Invoke, h => FooBar += h, h => FooBar -= h)
  25. .Subscribe()
  26. .AddTo(disposables); // IDisposable can add to collection easily by AddTo
  27. // convert to IO<EventArgs>, many situation this is useful than FromEventPattern
  28. Observable.FromEvent<EventHandler<MyEventArgs>, MyEventArgs>(
  29. h => (sender, e) => h(e), h => FooBar += h, h => FooBar -= h)
  30. .Subscribe()
  31. .AddTo(disposables);
  32. // You can convert Action like event.
  33. Observable.FromEvent<int>(
  34. h => FooFoo += h, h => FooFoo -= h)
  35. .Subscribe()
  36. .AddTo(disposables);
  37. // AOT Safe EventHandling, use dummy capture, see:https://github.com/neuecc/UniRx/wiki/AOT-Exception-Patterns-and-Hacks
  38. var capture = 0;
  39. Observable.FromEventPattern<EventHandler<MyEventArgs>, MyEventArgs>(h =>
  40. {
  41. capture.GetHashCode(); // dummy for AOT
  42. return new EventHandler<MyEventArgs>(h);
  43. }, h => FooBar += h, h => FooBar -= h)
  44. .Subscribe()
  45. .AddTo(disposables);
  46. // Subject as like event.
  47. OnBarBar.Subscribe().AddTo(disposables);
  48. onBarBar.OnNext(1); // fire event
  49. }
  50. void OnDestroy()
  51. {
  52. // manage subscription lifecycle
  53. disposables.Dispose();
  54. }
  55. }
  56. }
  57. #pragma warning restore 0067