| 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 DefaultIfEmpty<TSource> : Producer<TSource> |
| 9 |
{ |
| 10 |
private readonly IObservable<TSource> _source; |
| 11 |
private readonly TSource _defaultValue; |
| 12 |
|
| 13 |
public DefaultIfEmpty(IObservable<TSource> source, TSource defaultValue) |
| 14 |
{ |
| 15 |
_source = source; |
| 16 |
_defaultValue = defaultValue; |
| 17 |
} |
| 18 |
|
| 19 |
protected override IDisposable Run(IObserver<TSource> observer, IDisposable cancel, Action<IDisposable> setSink) |
| 20 |
{ |
| 21 |
var sink = new _(this, observer, cancel); |
| 22 |
setSink(sink); |
| 23 |
return _source.SubscribeSafe(sink); |
| 24 |
} |
| 25 |
|
| 26 |
class _ : Sink<TSource>, IObserver<TSource> |
| 27 |
{ |
| 28 |
private readonly DefaultIfEmpty<TSource> _parent; |
| 29 |
private bool _found; |
| 30 |
|
| 31 |
public _(DefaultIfEmpty<TSource> parent, IObserver<TSource> observer, IDisposable cancel) |
| 32 |
: base(observer, cancel) |
| 33 |
{ |
| 34 |
_parent = parent; |
| 35 |
_found = false; |
| 36 |
} |
| 37 |
|
| 38 |
public void OnNext(TSource value) |
| 39 |
{ |
| 40 |
_found = true; |
| 41 |
base._observer.OnNext(value); |
| 42 |
} |
| 43 |
|
| 44 |
public void OnError(Exception error) |
| 45 |
{ |
| 46 |
base._observer.OnError(error); |
| 47 |
base.Dispose(); |
| 48 |
} |
| 49 |
|
| 50 |
public void OnCompleted() |
| 51 |
{ |
| 52 |
if (!_found) |
| 53 |
base._observer.OnNext(_parent._defaultValue); |
| 54 |
base._observer.OnCompleted(); |
| 55 |
base.Dispose(); |
| 56 |
} |
| 57 |
} |
| 58 |
} |
| 59 |
} |
| 60 |
#endif |