Created
January 15, 2015 03:02
-
-
Save wilfrem/42f5b23d1a0b8fe6f760 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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