Cast.cs 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. // Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information.
  2. #if !NO_PERF
  3. using System;
  4. namespace System.Reactive.Linq.Observαble
  5. {
  6. class Cast<TSource, TResult> : Producer<TResult> /* Could optimize further by deriving from Select<TResult> and providing Ω<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. }
  53. #endif