DefaultIfEmpty.cs 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. using System;
  2. using UniRx.Operators;
  3. namespace UniRx.Operators
  4. {
  5. internal class DefaultIfEmptyObservable<T> : OperatorObservableBase<T>
  6. {
  7. readonly IObservable<T> source;
  8. readonly T defaultValue;
  9. public DefaultIfEmptyObservable(IObservable<T> source, T defaultValue)
  10. : base(source.IsRequiredSubscribeOnCurrentThread())
  11. {
  12. this.source = source;
  13. this.defaultValue = defaultValue;
  14. }
  15. protected override IDisposable SubscribeCore(IObserver<T> observer, IDisposable cancel)
  16. {
  17. return source.Subscribe(new DefaultIfEmpty(this, observer, cancel));
  18. }
  19. class DefaultIfEmpty : OperatorObserverBase<T, T>
  20. {
  21. readonly DefaultIfEmptyObservable<T> parent;
  22. bool hasValue;
  23. public DefaultIfEmpty(DefaultIfEmptyObservable<T> parent, IObserver<T> observer, IDisposable cancel) : base(observer, cancel)
  24. {
  25. this.parent = parent;
  26. this.hasValue = false;
  27. }
  28. public override void OnNext(T value)
  29. {
  30. hasValue = true;
  31. observer.OnNext(value);
  32. }
  33. public override void OnError(Exception error)
  34. {
  35. try { observer.OnError(error); }
  36. finally { Dispose(); }
  37. }
  38. public override void OnCompleted()
  39. {
  40. if (!hasValue)
  41. {
  42. observer.OnNext(parent.defaultValue);
  43. }
  44. try { observer.OnCompleted(); }
  45. finally { Dispose(); }
  46. }
  47. }
  48. }
  49. }