// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information. using System.Reactive.Disposables; namespace System.Reactive.Linq.ObservableImpl { internal sealed class If : Producer._>, IEvaluatableObservable { private readonly Func _condition; private readonly IObservable _thenSource; private readonly IObservable _elseSource; public If(Func condition, IObservable thenSource, IObservable elseSource) { _condition = condition; _thenSource = thenSource; _elseSource = elseSource; } public IObservable Eval() => _condition() ? _thenSource : _elseSource; protected override _ CreateSink(IObserver observer) => new _(this, observer); protected override void Run(_ sink) => sink.Run(); internal sealed class _ : IdentitySink { private readonly If _parent; public _(If parent, IObserver observer) : base(observer) { _parent = parent; } public void Run() { var result = default(IObservable); try { result = _parent.Eval(); } catch (Exception exception) { ForwardOnError(exception); return; } SetUpstream(result.SubscribeSafe(this)); } } } }