// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT License. // See the LICENSE file in the project root for more information. using System.Reactive.Disposables; using System.Reactive.Subjects; namespace System.Reactive.Linq.ObservableImpl { internal sealed class Multicast : Producer._> { private readonly IObservable _source; private readonly Func> _subjectSelector; private readonly Func, IObservable> _selector; public Multicast(IObservable source, Func> subjectSelector, Func, IObservable> selector) { _source = source; _subjectSelector = subjectSelector; _selector = selector; } protected override _ CreateSink(IObserver observer) => new(observer); protected override void Run(_ sink) => sink.Run(this); internal sealed class _ : IdentitySink { private SingleAssignmentDisposableValue _connection; public _(IObserver observer) : base(observer) { } public void Run(Multicast parent) { IObservable observable; IConnectableObservable connectable; try { var subject = parent._subjectSelector(); connectable = new ConnectableObservable(parent._source, subject); observable = parent._selector(connectable); } catch (Exception exception) { ForwardOnError(exception); return; } Run(observable); _connection.Disposable = connectable.Connect(); } protected override void Dispose(bool disposing) { if (disposing) { _connection.Dispose(); } base.Dispose(disposing); } } } }