DefaultIfEmpty.cs 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  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 DefaultIfEmpty<TSource> : Producer<TSource>
  9. {
  10. private readonly IObservable<TSource> _source;
  11. private readonly TSource _defaultValue;
  12. public DefaultIfEmpty(IObservable<TSource> source, TSource defaultValue)
  13. {
  14. _source = source;
  15. _defaultValue = defaultValue;
  16. }
  17. protected override IDisposable Run(IObserver<TSource> observer, IDisposable cancel, Action<IDisposable> setSink)
  18. {
  19. var sink = new _(this, observer, cancel);
  20. setSink(sink);
  21. return _source.SubscribeSafe(sink);
  22. }
  23. class _ : Sink<TSource>, IObserver<TSource>
  24. {
  25. private readonly DefaultIfEmpty<TSource> _parent;
  26. private bool _found;
  27. public _(DefaultIfEmpty<TSource> parent, IObserver<TSource> observer, IDisposable cancel)
  28. : base(observer, cancel)
  29. {
  30. _parent = parent;
  31. _found = false;
  32. }
  33. public void OnNext(TSource value)
  34. {
  35. _found = true;
  36. base._observer.OnNext(value);
  37. }
  38. public void OnError(Exception error)
  39. {
  40. base._observer.OnError(error);
  41. base.Dispose();
  42. }
  43. public void OnCompleted()
  44. {
  45. if (!_found)
  46. base._observer.OnNext(_parent._defaultValue);
  47. base._observer.OnCompleted();
  48. base.Dispose();
  49. }
  50. }
  51. }
  52. }
  53. #endif