1
0

Distinct.cs 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  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.Collections.Generic;
  5. namespace System.Reactive.Linq
  6. {
  7. public partial class AsyncObservable
  8. {
  9. public static IAsyncObservable<TSource> Distinct<TSource>(IAsyncObservable<TSource> source)
  10. {
  11. if (source == null)
  12. throw new ArgumentNullException(nameof(source));
  13. return Create(source, static (source, observer) => source.SubscribeSafeAsync(AsyncObserver.Distinct(observer)));
  14. }
  15. public static IAsyncObservable<TSource> Distinct<TSource>(IAsyncObservable<TSource> source, 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(
  22. source,
  23. comparer,
  24. static (source, comparer, observer) => source.SubscribeSafeAsync(AsyncObserver.Distinct(observer, comparer)));
  25. }
  26. }
  27. public partial class AsyncObserver
  28. {
  29. public static IAsyncObserver<TSource> Distinct<TSource>(IAsyncObserver<TSource> observer)
  30. {
  31. if (observer == null)
  32. throw new ArgumentNullException(nameof(observer));
  33. return Distinct(observer, EqualityComparer<TSource>.Default);
  34. }
  35. public static IAsyncObserver<TSource> Distinct<TSource>(IAsyncObserver<TSource> observer, IEqualityComparer<TSource> comparer)
  36. {
  37. if (observer == null)
  38. throw new ArgumentNullException(nameof(observer));
  39. if (comparer == null)
  40. throw new ArgumentNullException(nameof(comparer));
  41. var set = new HashSet<TSource>(comparer);
  42. return Create<TSource>(
  43. async x =>
  44. {
  45. var added = false;
  46. try
  47. {
  48. added = set.Add(x);
  49. }
  50. catch (Exception ex)
  51. {
  52. await observer.OnErrorAsync(ex).ConfigureAwait(false);
  53. return;
  54. }
  55. if (added)
  56. {
  57. await observer.OnNextAsync(x).ConfigureAwait(false);
  58. }
  59. },
  60. observer.OnErrorAsync,
  61. observer.OnCompletedAsync
  62. );
  63. }
  64. }
  65. }