ToList.cs 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  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.ObservableImpl
  6. {
  7. internal sealed class ToList<TSource> : Producer<IList<TSource>>
  8. {
  9. private readonly IObservable<TSource> _source;
  10. public ToList(IObservable<TSource> source)
  11. {
  12. _source = source;
  13. }
  14. protected override IDisposable Run(IObserver<IList<TSource>> observer, IDisposable cancel, Action<IDisposable> setSink)
  15. {
  16. var sink = new _(observer, cancel);
  17. setSink(sink);
  18. return _source.SubscribeSafe(sink);
  19. }
  20. private sealed class _ : Sink<IList<TSource>>, IObserver<TSource>
  21. {
  22. private List<TSource> _list;
  23. public _(IObserver<IList<TSource>> observer, IDisposable cancel)
  24. : base(observer, cancel)
  25. {
  26. _list = new List<TSource>();
  27. }
  28. public void OnNext(TSource value)
  29. {
  30. _list.Add(value);
  31. }
  32. public void OnError(Exception error)
  33. {
  34. base._observer.OnError(error);
  35. base.Dispose();
  36. }
  37. public void OnCompleted()
  38. {
  39. base._observer.OnNext(_list);
  40. base._observer.OnCompleted();
  41. base.Dispose();
  42. }
  43. }
  44. }
  45. }