| 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 |
using System.Reactive.Disposables; |
| 6 |
|
| 7 |
namespace System.Reactive.Linq.ObservableImpl |
| 8 |
{ |
| 9 |
class Using<TSource, TResource> : Producer<TSource> |
| 10 |
where TResource : IDisposable |
| 11 |
{ |
| 12 |
private readonly Func<TResource> _resourceFactory; |
| 13 |
private readonly Func<TResource, IObservable<TSource>> _observableFactory; |
| 14 |
|
| 15 |
public Using(Func<TResource> resourceFactory, Func<TResource, IObservable<TSource>> observableFactory) |
| 16 |
{ |
| 17 |
_resourceFactory = resourceFactory; |
| 18 |
_observableFactory = observableFactory; |
| 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 sink.Run(); |
| 26 |
} |
| 27 |
|
| 28 |
class _ : Sink<TSource>, IObserver<TSource> |
| 29 |
{ |
| 30 |
private readonly Using<TSource, TResource> _parent; |
| 31 |
|
| 32 |
public _(Using<TSource, TResource> parent, IObserver<TSource> observer, IDisposable cancel) |
| 33 |
: base(observer, cancel) |
| 34 |
{ |
| 35 |
_parent = parent; |
| 36 |
} |
| 37 |
|
| 38 |
public IDisposable Run() |
| 39 |
{ |
| 40 |
var source = default(IObservable<TSource>); |
| 41 |
var disposable = Disposable.Empty; |
| 42 |
try |
| 43 |
{ |
| 44 |
var resource = _parent._resourceFactory(); |
| 45 |
if (resource != null) |
| 46 |
disposable = resource; |
| 47 |
source = _parent._observableFactory(resource); |
| 48 |
} |
| 49 |
catch (Exception exception) |
| 50 |
{ |
| 51 |
return new CompositeDisposable(Observable.Throw<TSource>(exception).SubscribeSafe(this), disposable); |
| 52 |
} |
| 53 |
|
| 54 |
return new CompositeDisposable(source.SubscribeSafe(this), disposable); |
| 55 |
} |
| 56 |
|
| 57 |
public void OnNext(TSource value) |
| 58 |
{ |
| 59 |
base._observer.OnNext(value); |
| 60 |
} |
| 61 |
|
| 62 |
public void OnError(Exception error) |
| 63 |
{ |
| 64 |
base._observer.OnError(error); |
| 65 |
base.Dispose(); |
| 66 |
} |
| 67 |
|
| 68 |
public void OnCompleted() |
| 69 |
{ |
| 70 |
base._observer.OnCompleted(); |
| 71 |
base.Dispose(); |
| 72 |
} |
| 73 |
} |
| 74 |
} |
| 75 |
} |
| 76 |
#endif |