DefaultIfEmpty.cs 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  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. using System.Collections.Generic;
  5. namespace System.Reactive.Linq
  6. {
  7. partial class AsyncObservable
  8. {
  9. public static IAsyncObservable<TSource> DefaultIfEmpty<TSource>(this IAsyncObservable<TSource> source)
  10. {
  11. if (source == null)
  12. throw new ArgumentNullException(nameof(source));
  13. return Create<TSource>(observer => source.SubscribeAsync(AsyncObserver.DefaultIfEmpty<TSource>(observer)));
  14. }
  15. public static IAsyncObservable<TSource> DefaultIfEmpty<TSource>(this IAsyncObservable<TSource> source, TSource defaultValue)
  16. {
  17. if (source == null)
  18. throw new ArgumentNullException(nameof(source));
  19. return Create<TSource>(observer => source.SubscribeAsync(AsyncObserver.DefaultIfEmpty<TSource>(observer, defaultValue)));
  20. }
  21. }
  22. partial class AsyncObserver
  23. {
  24. public static IAsyncObserver<TSource> DefaultIfEmpty<TSource>(this IAsyncObserver<TSource> observer)
  25. {
  26. if (observer == null)
  27. throw new ArgumentNullException(nameof(observer));
  28. return DefaultIfEmpty(observer, default(TSource));
  29. }
  30. public static IAsyncObserver<TSource> DefaultIfEmpty<TSource>(this IAsyncObserver<TSource> observer, TSource defaultValue)
  31. {
  32. if (observer == null)
  33. throw new ArgumentNullException(nameof(observer));
  34. var hasValue = false;
  35. return Create<TSource>(
  36. x =>
  37. {
  38. hasValue = true;
  39. return observer.OnNextAsync(x);
  40. },
  41. observer.OnErrorAsync,
  42. async () =>
  43. {
  44. if (!hasValue)
  45. {
  46. await observer.OnNextAsync(defaultValue).ConfigureAwait(false);
  47. }
  48. await observer.OnCompletedAsync().ConfigureAwait(false);
  49. }
  50. );
  51. }
  52. }
  53. }