AsObservable.cs 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  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. namespace System.Reactive.Linq.ObservableImpl
  5. {
  6. internal sealed class AsObservable<TSource> : Producer<TSource>, IEvaluatableObservable<TSource>
  7. {
  8. private readonly IObservable<TSource> _source;
  9. public AsObservable(IObservable<TSource> source)
  10. {
  11. _source = source;
  12. }
  13. public IObservable<TSource> Eval() => _source;
  14. protected override IDisposable CreateSink(IObserver<TSource> observer, IDisposable cancel) => new _(observer, cancel);
  15. protected override IDisposable Run(IObserver<TSource> observer, IDisposable cancel, Action<IDisposable> setSink)
  16. {
  17. var sink = new _(observer, cancel);
  18. setSink(sink);
  19. return _source.SubscribeSafe(sink);
  20. }
  21. private sealed class _ : Sink<TSource>, IObserver<TSource>
  22. {
  23. public _(IObserver<TSource> observer, IDisposable cancel)
  24. : base(observer, cancel)
  25. {
  26. }
  27. public void OnNext(TSource value)
  28. {
  29. base._observer.OnNext(value);
  30. }
  31. public void OnError(Exception error)
  32. {
  33. base._observer.OnError(error);
  34. base.Dispose();
  35. }
  36. public void OnCompleted()
  37. {
  38. base._observer.OnCompleted();
  39. base.Dispose();
  40. }
  41. }
  42. }
  43. }