Cast.cs 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  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 Cast<TSource, TResult> : Producer<TResult, Cast<TSource, TResult>._> /* Could optimize further by deriving from Select<TResult> and providing Combine<TResult2>. We're not doing this (yet) for debuggability. */
  7. {
  8. private readonly IObservable<TSource> _source;
  9. public Cast(IObservable<TSource> source)
  10. {
  11. _source = source;
  12. }
  13. protected override _ CreateSink(IObserver<TResult> observer, IDisposable cancel) => new _(observer, cancel);
  14. protected override IDisposable Run(_ sink) => _source.SubscribeSafe(sink);
  15. internal sealed class _ : Sink<TResult>, IObserver<TSource>
  16. {
  17. public _(IObserver<TResult> observer, IDisposable cancel)
  18. : base(observer, cancel)
  19. {
  20. }
  21. public void OnNext(TSource value)
  22. {
  23. var result = default(TResult);
  24. try
  25. {
  26. result = (TResult)(object)value;
  27. }
  28. catch (Exception exception)
  29. {
  30. base._observer.OnError(exception);
  31. base.Dispose();
  32. return;
  33. }
  34. base._observer.OnNext(result);
  35. }
  36. public void OnError(Exception error)
  37. {
  38. base._observer.OnError(error);
  39. base.Dispose();
  40. }
  41. public void OnCompleted()
  42. {
  43. base._observer.OnCompleted();
  44. base.Dispose();
  45. }
  46. }
  47. }
  48. }