Using.cs 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  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. using System.Reactive.Disposables;
  6. namespace System.Reactive.Linq.ObservableImpl
  7. {
  8. internal sealed class Using<TSource, TResource> : Producer<TSource>
  9. where TResource : IDisposable
  10. {
  11. private readonly Func<TResource> _resourceFactory;
  12. private readonly Func<TResource, IObservable<TSource>> _observableFactory;
  13. public Using(Func<TResource> resourceFactory, Func<TResource, IObservable<TSource>> observableFactory)
  14. {
  15. _resourceFactory = resourceFactory;
  16. _observableFactory = observableFactory;
  17. }
  18. protected override IDisposable Run(IObserver<TSource> observer, IDisposable cancel, Action<IDisposable> setSink)
  19. {
  20. var sink = new _(this, observer, cancel);
  21. setSink(sink);
  22. return sink.Run();
  23. }
  24. class _ : Sink<TSource>, IObserver<TSource>
  25. {
  26. private readonly Using<TSource, TResource> _parent;
  27. public _(Using<TSource, TResource> parent, IObserver<TSource> observer, IDisposable cancel)
  28. : base(observer, cancel)
  29. {
  30. _parent = parent;
  31. }
  32. public IDisposable Run()
  33. {
  34. var source = default(IObservable<TSource>);
  35. var disposable = Disposable.Empty;
  36. try
  37. {
  38. var resource = _parent._resourceFactory();
  39. if (resource != null)
  40. disposable = resource;
  41. source = _parent._observableFactory(resource);
  42. }
  43. catch (Exception exception)
  44. {
  45. return StableCompositeDisposable.Create(Observable.Throw<TSource>(exception).SubscribeSafe(this), disposable);
  46. }
  47. return StableCompositeDisposable.Create(source.SubscribeSafe(this), disposable);
  48. }
  49. public void OnNext(TSource value)
  50. {
  51. base._observer.OnNext(value);
  52. }
  53. public void OnError(Exception error)
  54. {
  55. base._observer.OnError(error);
  56. base.Dispose();
  57. }
  58. public void OnCompleted()
  59. {
  60. base._observer.OnCompleted();
  61. base.Dispose();
  62. }
  63. }
  64. }
  65. }