DefaultIfEmpty.cs 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. // Licensed to the .NET Foundation under one or more agreements.
  2. // The .NET Foundation licenses this file to you under the MIT License.
  3. // See the LICENSE file in the project root for more information.
  4. namespace System.Reactive.Linq.ObservableImpl
  5. {
  6. internal sealed class DefaultIfEmpty<TSource> : Producer<TSource, DefaultIfEmpty<TSource>._>
  7. {
  8. private readonly IObservable<TSource> _source;
  9. private readonly TSource _defaultValue;
  10. public DefaultIfEmpty(IObservable<TSource> source, TSource defaultValue)
  11. {
  12. _source = source;
  13. _defaultValue = defaultValue;
  14. }
  15. protected override _ CreateSink(IObserver<TSource> observer) => new _(_defaultValue, observer);
  16. protected override void Run(_ sink) => sink.Run(_source);
  17. internal sealed class _ : IdentitySink<TSource>
  18. {
  19. private readonly TSource _defaultValue;
  20. private bool _found;
  21. public _(TSource defaultValue, IObserver<TSource> observer)
  22. : base(observer)
  23. {
  24. _defaultValue = defaultValue;
  25. _found = false;
  26. }
  27. public override void OnNext(TSource value)
  28. {
  29. _found = true;
  30. ForwardOnNext(value);
  31. }
  32. public override void OnCompleted()
  33. {
  34. if (!_found)
  35. {
  36. ForwardOnNext(_defaultValue);
  37. }
  38. ForwardOnCompleted();
  39. }
  40. }
  41. }
  42. }