using System; namespace UniRx.Operators { internal class DeferObservable : OperatorObservableBase { readonly Func> observableFactory; public DeferObservable(Func> observableFactory) : base(false) { this.observableFactory = observableFactory; } protected override IDisposable SubscribeCore(IObserver observer, IDisposable cancel) { observer = new Defer(observer, cancel); IObservable source; try { source = observableFactory(); } catch (Exception ex) { source = Observable.Throw(ex); } return source.Subscribe(observer); } class Defer : OperatorObserverBase { public Defer(IObserver observer, IDisposable cancel) : base(observer, cancel) { } public override void OnNext(T value) { try { base.observer.OnNext(value); } catch { Dispose(); throw; } } public override void OnError(Exception error) { try { observer.OnError(error); } finally { Dispose(); } } public override void OnCompleted() { try { observer.OnCompleted(); } finally { Dispose(); } } } } }