Distinct.cs 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  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<TSource> Distinct<TSource>(IAsyncObservable<TSource> source)
  10. {
  11. if (source == null)
  12. throw new ArgumentNullException(nameof(source));
  13. return Create<TSource>(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<TSource>(observer => source.SubscribeSafeAsync(AsyncObserver.Distinct(observer, comparer)));
  22. }
  23. }
  24. partial class AsyncObserver
  25. {
  26. public static IAsyncObserver<TSource> Distinct<TSource>(IAsyncObserver<TSource> observer)
  27. {
  28. if (observer == null)
  29. throw new ArgumentNullException(nameof(observer));
  30. return Distinct(observer, EqualityComparer<TSource>.Default);
  31. }
  32. public static IAsyncObserver<TSource> Distinct<TSource>(IAsyncObserver<TSource> observer, 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. var set = new HashSet<TSource>(comparer);
  39. return Create<TSource>(
  40. async x =>
  41. {
  42. var added = false;
  43. try
  44. {
  45. added = set.Add(x);
  46. }
  47. catch (Exception ex)
  48. {
  49. await observer.OnErrorAsync(ex).ConfigureAwait(false);
  50. return;
  51. }
  52. if (added)
  53. {
  54. await observer.OnNextAsync(x).ConfigureAwait(false);
  55. }
  56. },
  57. observer.OnErrorAsync,
  58. observer.OnCompletedAsync
  59. );
  60. }
  61. }
  62. }