Skip to content

Instantly share code, notes, and snippets.

@wilfrem
Created January 15, 2015 03:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wilfrem/42f5b23d1a0b8fe6f760 to your computer and use it in GitHub Desktop.
Save wilfrem/42f5b23d1a0b8fe6f760 to your computer and use it in GitHub Desktop.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
namespace UniRxEx
{
public static partial class Observable
{
public static IObservable<T> RefCountEx<T>(this IConnectableObservable<T> source)
{
var connection = source.Connect();
var gate = new object();
var refCount = 0;
var flag = false;
return Observable.Create<T>(observer =>
{
var subscription = source.Subscribe(observer);
lock (gate)
{
if (++refCount == 1 && flag)
{
connection = source.Connect();
}
}
return Disposable.Create(() =>
{
subscription.Dispose();
lock (gate)
{
if (--refCount == 0)
{
connection.Dispose(); // connection isn't null.
flag = true;
}
}
});
});
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment