Cast.cs 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  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> /* 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 IDisposable Run(IObserver<TResult> observer, IDisposable cancel, Action<IDisposable> setSink)
  14. {
  15. var sink = new _(observer, cancel);
  16. setSink(sink);
  17. return _source.SubscribeSafe(sink);
  18. }
  19. class _ : Sink<TResult>, IObserver<TSource>
  20. {
  21. public _(IObserver<TResult> observer, IDisposable cancel)
  22. : base(observer, cancel)
  23. {
  24. }
  25. public void OnNext(TSource value)
  26. {
  27. var result = default(TResult);
  28. try
  29. {
  30. result = (TResult)(object)value;
  31. }
  32. catch (Exception exception)
  33. {
  34. base._observer.OnError(exception);
  35. base.Dispose();
  36. return;
  37. }
  38. base._observer.OnNext(result);
  39. }
  40. public void OnError(Exception error)
  41. {
  42. base._observer.OnError(error);
  43. base.Dispose();
  44. }
  45. public void OnCompleted()
  46. {
  47. base._observer.OnCompleted();
  48. base.Dispose();
  49. }
  50. }
  51. }
  52. }