All.cs 3.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  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.Threading.Tasks;
  5. namespace System.Reactive.Linq
  6. {
  7. partial class AsyncObservable
  8. {
  9. public static IAsyncObservable<bool> All<TSource>(this IAsyncObservable<TSource> source, Func<TSource, bool> predicate)
  10. {
  11. if (source == null)
  12. throw new ArgumentNullException(nameof(source));
  13. if (predicate == null)
  14. throw new ArgumentNullException(nameof(predicate));
  15. return Create<bool>(observer => source.SubscribeSafeAsync(AsyncObserver.All(observer, predicate)));
  16. }
  17. public static IAsyncObservable<bool> All<TSource>(this IAsyncObservable<TSource> source, Func<TSource, Task<bool>> predicate)
  18. {
  19. if (source == null)
  20. throw new ArgumentNullException(nameof(source));
  21. if (predicate == null)
  22. throw new ArgumentNullException(nameof(predicate));
  23. return Create<bool>(observer => source.SubscribeSafeAsync(AsyncObserver.All(observer, predicate)));
  24. }
  25. }
  26. partial class AsyncObserver
  27. {
  28. public static IAsyncObserver<TSource> All<TSource>(IAsyncObserver<bool> observer, Func<TSource, bool> predicate)
  29. {
  30. if (observer == null)
  31. throw new ArgumentNullException(nameof(observer));
  32. if (predicate == null)
  33. throw new ArgumentNullException(nameof(predicate));
  34. return All<TSource>(observer, x => Task.FromResult(predicate(x)));
  35. }
  36. public static IAsyncObserver<TSource> All<TSource>(IAsyncObserver<bool> observer, Func<TSource, Task<bool>> predicate)
  37. {
  38. if (observer == null)
  39. throw new ArgumentNullException(nameof(observer));
  40. if (predicate == null)
  41. throw new ArgumentNullException(nameof(predicate));
  42. return Create<TSource>(
  43. async x =>
  44. {
  45. var b = default(bool);
  46. try
  47. {
  48. b = await predicate(x).ConfigureAwait(false);
  49. }
  50. catch (Exception ex)
  51. {
  52. await observer.OnErrorAsync(ex).ConfigureAwait(false);
  53. return;
  54. }
  55. if (!b)
  56. {
  57. await observer.OnNextAsync(false).ConfigureAwait(false);
  58. await observer.OnCompletedAsync().ConfigureAwait(false);
  59. }
  60. },
  61. observer.OnErrorAsync,
  62. async () =>
  63. {
  64. await observer.OnNextAsync(true).ConfigureAwait(false);
  65. await observer.OnCompletedAsync().ConfigureAwait(false);
  66. }
  67. );
  68. }
  69. }
  70. }