Using.cs 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  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.Reactive.Disposables;
  5. namespace System.Reactive.Linq.ObservableImpl
  6. {
  7. internal sealed class Using<TSource, TResource> : Producer<TSource, Using<TSource, TResource>._>
  8. where TResource : IDisposable
  9. {
  10. private readonly Func<TResource> _resourceFactory;
  11. private readonly Func<TResource, IObservable<TSource>> _observableFactory;
  12. public Using(Func<TResource> resourceFactory, Func<TResource, IObservable<TSource>> observableFactory)
  13. {
  14. _resourceFactory = resourceFactory;
  15. _observableFactory = observableFactory;
  16. }
  17. protected override _ CreateSink(IObserver<TSource> observer) => new _(observer);
  18. protected override void Run(_ sink) => sink.Run(this);
  19. internal sealed class _ : IdentitySink<TSource>
  20. {
  21. public _(IObserver<TSource> observer)
  22. : base(observer)
  23. {
  24. }
  25. private IDisposable _disposable;
  26. public void Run(Using<TSource, TResource> parent)
  27. {
  28. var source = default(IObservable<TSource>);
  29. try
  30. {
  31. var resource = parent._resourceFactory();
  32. if (resource != null)
  33. Disposable.SetSingle(ref _disposable, resource);
  34. source = parent._observableFactory(resource);
  35. }
  36. catch (Exception exception)
  37. {
  38. SetUpstream(Observable.Throw<TSource>(exception).SubscribeSafe(this));
  39. return;
  40. }
  41. base.Run(source);
  42. }
  43. protected override void Dispose(bool disposing)
  44. {
  45. if (disposing)
  46. {
  47. Disposable.TryDispose(ref _disposable);
  48. }
  49. base.Dispose(disposing);
  50. }
  51. }
  52. }
  53. }