Skip to content

Commit

Permalink
fix bug of RefCount
Browse files Browse the repository at this point in the history
  • Loading branch information
neuecc committed Aug 15, 2024
1 parent 198a489 commit 8ce34ae
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 10 deletions.
29 changes: 21 additions & 8 deletions sandbox/ConsoleApp1/Program.cs
Original file line number Diff line number Diff line change
@@ -1,18 +1,31 @@
using R3;
//using System.Reactive.Linq;
using System.Diagnostics;
using System.Threading.Channels;
using System.Xml.Serialization;



string[] array = { "a", "b", "c" };
array
.ToObservable()
.SubscribeAwait(static async (element, token) =>
{
Console.WriteLine(element);
await Task.Yield();
}, AwaitOperation.Sequential);
var doScan = Observable.FromAsync(async (token) =>
{
Console.WriteLine("scan start");
await Task.Delay(TimeSpan.FromSeconds(3));
Console.WriteLine("scan end");
return 5;
});

var doCalc = Observable.FromAsync(async (token) =>
{
Console.WriteLine("calc start");
await Task.Delay(TimeSpan.FromSeconds(3), token);
Console.WriteLine("calc end");
return 10;
});

var countDown = Observable.Interval(TimeSpan.FromMilliseconds(300)).Index().Select(v => v > 9 ? 9 : v);

var work = doScan.Select(_ => doCalc).Switch().Replay(1).RefCount();
countDown.TakeUntil(work.LastAsync()).Concat(work.TakeLast(1)).Subscribe(v => Console.WriteLine($"progress: {v}"));


Console.ReadLine();
8 changes: 6 additions & 2 deletions src/R3/Operators/RefCount.cs
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,12 @@ protected override IDisposable SubscribeCore(Observer<T> observer)
{
lock (gate)
{
var subcription = source.Subscribe(new _RefCount(this, observer));
if (++refCount == 1)
// incr refCount before Subscribe(completed source decrement refCount in Subscribe)
++refCount;
bool needConnect = refCount == 1;
var coObserver = new _RefCount(this, observer);
var subcription = source.Subscribe(coObserver);
if (needConnect && !coObserver.IsDisposed)
{
connection = source.Connect();
}
Expand Down

0 comments on commit 8ce34ae

Please sign in to comment.