| 1 |
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information. |
| 2 |
|
| 3 |
#if !NO_PERF |
| 4 |
using System; |
| 5 |
|
| 6 |
namespace System.Reactive.Linq.ObservableImpl |
| 7 |
{ |
| 8 |
class ElementAt<TSource> : Producer<TSource> |
| 9 |
{ |
| 10 |
private readonly IObservable<TSource> _source; |
| 11 |
private readonly int _index; |
| 12 |
private readonly bool _throwOnEmpty; |
| 13 |
|
| 14 |
public ElementAt(IObservable<TSource> source, int index, bool throwOnEmpty) |
| 15 |
{ |
| 16 |
_source = source; |
| 17 |
_index = index; |
| 18 |
_throwOnEmpty = throwOnEmpty; |
| 19 |
} |
| 20 |
|
| 21 |
protected override IDisposable Run(IObserver<TSource> observer, IDisposable cancel, Action<IDisposable> setSink) |
| 22 |
{ |
| 23 |
var sink = new _(this, observer, cancel); |
| 24 |
setSink(sink); |
| 25 |
return _source.SubscribeSafe(sink); |
| 26 |
} |
| 27 |
|
| 28 |
class _ : Sink<TSource>, IObserver<TSource> |
| 29 |
{ |
| 30 |
private readonly ElementAt<TSource> _parent; |
| 31 |
private int _i; |
| 32 |
|
| 33 |
public _(ElementAt<TSource> parent, IObserver<TSource> observer, IDisposable cancel) |
| 34 |
: base(observer, cancel) |
| 35 |
{ |
| 36 |
_parent = parent; |
| 37 |
_i = _parent._index; |
| 38 |
} |
| 39 |
|
| 40 |
public void OnNext(TSource value) |
| 41 |
{ |
| 42 |
if (_i == 0) |
| 43 |
{ |
| 44 |
base._observer.OnNext(value); |
| 45 |
base._observer.OnCompleted(); |
| 46 |
base.Dispose(); |
| 47 |
} |
| 48 |
|
| 49 |
_i--; |
| 50 |
} |
| 51 |
|
| 52 |
public void OnError(Exception error) |
| 53 |
{ |
| 54 |
base._observer.OnError(error); |
| 55 |
base.Dispose(); |
| 56 |
} |
| 57 |
|
| 58 |
public void OnCompleted() |
| 59 |
{ |
| 60 |
if (_parent._throwOnEmpty) |
| 61 |
{ |
| 62 |
base._observer.OnError(new ArgumentOutOfRangeException("index")); |
| 63 |
} |
| 64 |
else |
| 65 |
{ |
| 66 |
base._observer.OnNext(default(TSource)); |
| 67 |
base._observer.OnCompleted(); |
| 68 |
} |
| 69 |
|
| 70 |
base.Dispose(); |
| 71 |
} |
| 72 |
} |
| 73 |
} |
| 74 |
} |
| 75 |
#endif |