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