If.cs 3.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  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. using System.Reactive.Concurrency;
  5. using System.Threading.Tasks;
  6. namespace System.Reactive.Linq
  7. {
  8. partial class AsyncObservable
  9. {
  10. public static IAsyncObservable<TResult> If<TResult>(Func<bool> condition, IAsyncObservable<TResult> thenSource) => If(condition, thenSource, Empty<TResult>());
  11. public static IAsyncObservable<TResult> If<TResult>(Func<bool> condition, IAsyncObservable<TResult> thenSource, IAsyncScheduler scheduler) => If(condition, thenSource, Empty<TResult>(scheduler));
  12. public static IAsyncObservable<TResult> If<TResult>(Func<bool> condition, IAsyncObservable<TResult> thenSource, IAsyncObservable<TResult> elseSource)
  13. {
  14. if (condition == null)
  15. throw new ArgumentNullException(nameof(condition));
  16. if (thenSource == null)
  17. throw new ArgumentNullException(nameof(thenSource));
  18. if (elseSource == null)
  19. throw new ArgumentNullException(nameof(elseSource));
  20. return Create<TResult>(observer =>
  21. {
  22. var b = default(bool);
  23. try
  24. {
  25. b = condition();
  26. }
  27. catch (Exception ex)
  28. {
  29. return Throw<TResult>(ex).SubscribeAsync(observer);
  30. }
  31. return (b ? thenSource : elseSource).SubscribeSafeAsync(observer);
  32. });
  33. }
  34. public static IAsyncObservable<TResult> If<TResult>(Func<Task<bool>> condition, IAsyncObservable<TResult> thenSource) => If(condition, thenSource, Empty<TResult>());
  35. public static IAsyncObservable<TResult> If<TResult>(Func<Task<bool>> condition, IAsyncObservable<TResult> thenSource, IAsyncScheduler scheduler) => If(condition, thenSource, Empty<TResult>(scheduler));
  36. public static IAsyncObservable<TResult> If<TResult>(Func<Task<bool>> condition, IAsyncObservable<TResult> thenSource, IAsyncObservable<TResult> elseSource)
  37. {
  38. if (condition == null)
  39. throw new ArgumentNullException(nameof(condition));
  40. if (thenSource == null)
  41. throw new ArgumentNullException(nameof(thenSource));
  42. if (elseSource == null)
  43. throw new ArgumentNullException(nameof(elseSource));
  44. return Create<TResult>(async observer =>
  45. {
  46. var b = default(bool);
  47. try
  48. {
  49. b = await condition().ConfigureAwait(false);
  50. }
  51. catch (Exception ex)
  52. {
  53. return await Throw<TResult>(ex).SubscribeAsync(observer).ConfigureAwait(false);
  54. }
  55. return await (b ? thenSource : elseSource).SubscribeSafeAsync(observer).ConfigureAwait(false);
  56. });
  57. }
  58. }
  59. }