SafeObserver.cs 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. // Licensed to the .NET Foundation under one or more agreements.
  2. // The .NET Foundation licenses this file to you under the Apache 2.0 License.
  3. // See the LICENSE file in the project root for more information.
  4. using System;
  5. namespace System.Reactive
  6. {
  7. //
  8. // See AutoDetachObserver.cs for more information on the safeguarding requirement and
  9. // its implementation aspects.
  10. //
  11. class SafeObserver<TSource> : IObserver<TSource>
  12. {
  13. private readonly IObserver<TSource> _observer;
  14. private readonly IDisposable _disposable;
  15. public static IObserver<TSource> Create(IObserver<TSource> observer, IDisposable disposable)
  16. {
  17. var a = observer as AnonymousObserver<TSource>;
  18. if (a != null)
  19. return a.MakeSafe(disposable);
  20. else
  21. return new SafeObserver<TSource>(observer, disposable);
  22. }
  23. private SafeObserver(IObserver<TSource> observer, IDisposable disposable)
  24. {
  25. _observer = observer;
  26. _disposable = disposable;
  27. }
  28. public void OnNext(TSource value)
  29. {
  30. var __noError = false;
  31. try
  32. {
  33. _observer.OnNext(value);
  34. __noError = true;
  35. }
  36. finally
  37. {
  38. if (!__noError)
  39. _disposable.Dispose();
  40. }
  41. }
  42. public void OnError(Exception error)
  43. {
  44. try
  45. {
  46. _observer.OnError(error);
  47. }
  48. finally
  49. {
  50. _disposable.Dispose();
  51. }
  52. }
  53. public void OnCompleted()
  54. {
  55. try
  56. {
  57. _observer.OnCompleted();
  58. }
  59. finally
  60. {
  61. _disposable.Dispose();
  62. }
  63. }
  64. }
  65. }