ToList.cs 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  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>, ToList<TSource>._>
  8. {
  9. private readonly IObservable<TSource> _source;
  10. public ToList(IObservable<TSource> source)
  11. {
  12. _source = source;
  13. }
  14. protected override _ CreateSink(IObserver<IList<TSource>> observer) => new _(observer);
  15. protected override void Run(_ sink) => sink.Run(_source);
  16. internal sealed class _ : Sink<TSource, IList<TSource>>
  17. {
  18. private List<TSource> _list;
  19. public _(IObserver<IList<TSource>> observer)
  20. : base(observer)
  21. {
  22. _list = new List<TSource>();
  23. }
  24. public override void OnNext(TSource value)
  25. {
  26. _list.Add(value);
  27. }
  28. public override void OnError(Exception error)
  29. {
  30. _list = null;
  31. ForwardOnError(error);
  32. }
  33. public override void OnCompleted()
  34. {
  35. var list = _list;
  36. _list = null;
  37. ForwardOnNext(list);
  38. ForwardOnCompleted();
  39. }
  40. }
  41. }
  42. }