Contains.cs 2.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  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<bool> Contains<TSource>(this IAsyncObservable<TSource> source, TSource element)
  10. {
  11. if (source == null)
  12. throw new ArgumentNullException(nameof(source));
  13. return Create<bool>(observer => source.SubscribeSafeAsync(AsyncObserver.Contains<TSource>(observer, element)));
  14. }
  15. public static IAsyncObservable<bool> Contains<TSource>(this IAsyncObservable<TSource> source, TSource element, IEqualityComparer<TSource> comparer)
  16. {
  17. if (source == null)
  18. throw new ArgumentNullException(nameof(source));
  19. if (comparer == null)
  20. throw new ArgumentNullException(nameof(comparer));
  21. return Create<bool>(observer => source.SubscribeSafeAsync(AsyncObserver.Contains<TSource>(observer, element, comparer)));
  22. }
  23. }
  24. partial class AsyncObserver
  25. {
  26. public static IAsyncObserver<TSource> Contains<TSource>(IAsyncObserver<bool> observer, TSource element)
  27. {
  28. if (observer == null)
  29. throw new ArgumentNullException(nameof(observer));
  30. return Contains(observer, element, EqualityComparer<TSource>.Default);
  31. }
  32. public static IAsyncObserver<TSource> Contains<TSource>(IAsyncObserver<bool> observer, TSource element, IEqualityComparer<TSource> comparer)
  33. {
  34. if (observer == null)
  35. throw new ArgumentNullException(nameof(observer));
  36. if (comparer == null)
  37. throw new ArgumentNullException(nameof(comparer));
  38. return Create<TSource>(
  39. async x =>
  40. {
  41. var equals = false;
  42. try
  43. {
  44. equals = comparer.Equals(x, element);
  45. }
  46. catch (Exception ex)
  47. {
  48. await observer.OnErrorAsync(ex).ConfigureAwait(false);
  49. return;
  50. }
  51. if (equals)
  52. {
  53. await observer.OnNextAsync(true).ConfigureAwait(false);
  54. await observer.OnCompletedAsync().ConfigureAwait(false);
  55. }
  56. },
  57. observer.OnErrorAsync,
  58. async () =>
  59. {
  60. await observer.OnNextAsync(false).ConfigureAwait(false);
  61. await observer.OnCompletedAsync().ConfigureAwait(false);
  62. }
  63. );
  64. }
  65. }
  66. }