Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

4.x: Add the IConnectableObservable.AutoConnect() operator #497

Merged
merged 1 commit into from
May 26, 2018

Conversation

akarnokd
Copy link
Collaborator

@akarnokd akarnokd commented May 7, 2018

This PR adds the AutoConnect operator as an extension method on IConnectableObservable. The operator connects the source once the specified number of observers have subscribed to it.

This operator enables caching of items via Replay() without the need to call Connect() manually and avoid reconnection which would happen with RefCount():

var cached = source.Replay().AutoConnect(2);

// connection happens only now
cached.Subscribe(Console.WriteLine);

// connection happens only now
cached.Subscribe(Console.WriteLine);

// some time later when the source has completed on its own
// this will not trigger a new connection
cached.Subscribe(Console.WriteLine);

Subscribers disposed won't dispose the connection. In case the connection itself should be disposed, it is made available via the onConnect callback:

SingleAssingmentDisposable sad = new SingleAssignmentDisposable();

var cached = source.Replay().AutoConnect(1, d => sad.Disposable = d);

var d = source.Subscribe(Console.WriteLine);

// sometime later
// it would be recommended to dispose any observers because 
// they would stay without any further events and never terminate
d.Dispose();

// stop the source
sad.Dispose();

After this, the cache cannot be resurrected and a new chain has to be created again off of source.

@clairernovotny clairernovotny merged commit 3964f9f into dotnet:master May 26, 2018
@akarnokd akarnokd deleted the AutoConnect branch May 26, 2018 14:55
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants