1
0

Disposable.cs 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. using System;
  2. using System.Collections;
  3. namespace UniRx
  4. {
  5. public static class Disposable
  6. {
  7. public static readonly IDisposable Empty = EmptyDisposable.Singleton;
  8. public static IDisposable Create(Action disposeAction)
  9. {
  10. return new AnonymousDisposable(disposeAction);
  11. }
  12. public static IDisposable CreateWithState<TState>(TState state, Action<TState> disposeAction)
  13. {
  14. return new AnonymousDisposable<TState>(state, disposeAction);
  15. }
  16. class EmptyDisposable : IDisposable
  17. {
  18. public static EmptyDisposable Singleton = new EmptyDisposable();
  19. private EmptyDisposable()
  20. {
  21. }
  22. public void Dispose()
  23. {
  24. }
  25. }
  26. class AnonymousDisposable : IDisposable
  27. {
  28. bool isDisposed = false;
  29. readonly Action dispose;
  30. public AnonymousDisposable(Action dispose)
  31. {
  32. this.dispose = dispose;
  33. }
  34. public void Dispose()
  35. {
  36. if (!isDisposed)
  37. {
  38. isDisposed = true;
  39. dispose();
  40. }
  41. }
  42. }
  43. class AnonymousDisposable<T> : IDisposable
  44. {
  45. bool isDisposed = false;
  46. readonly T state;
  47. readonly Action<T> dispose;
  48. public AnonymousDisposable(T state, Action<T> dispose)
  49. {
  50. this.state = state;
  51. this.dispose = dispose;
  52. }
  53. public void Dispose()
  54. {
  55. if (!isDisposed)
  56. {
  57. isDisposed = true;
  58. dispose(state);
  59. }
  60. }
  61. }
  62. }
  63. }