DefaultIfEmpty.cs 2.1 KB

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