【发布时间】:2016-03-01 07:10:11
【问题描述】:
考虑以下几点:
[Fact]
public void foo()
{
var result = new Subject<bool>();
var startCount = 0;
var completionCount = 0;
var obs = Observable
.Defer(() =>
{
++startCount;
return result.FirstAsync();
})
.Do(_ => ++completionCount)
.Publish()
.RefCount();
// pretend there are lots of subscribers at once
var s1 = obs.Subscribe();
var s2 = obs.Subscribe();
var s3 = obs.Subscribe();
// even so, we only expect to be started once
Assert.Equal(1, startCount);
Assert.Equal(0, completionCount);
// and we won't complete until the result ticks through
result.OnNext(true);
Assert.Equal(1, startCount);
Assert.Equal(1, completionCount);
s1.Dispose();
s2.Dispose();
s3.Dispose();
// now try exactly the same thing again
s1 = obs.Subscribe();
s2 = obs.Subscribe();
s3 = obs.Subscribe();
// startCount is 4 here instead of the expected 2!
Assert.Equal(2, startCount);
Assert.Equal(1, completionCount);
result.OnNext(true);
Assert.Equal(2, startCount);
Assert.Equal(2, completionCount);
s1.Dispose();
s2.Dispose();
s3.Dispose();
}
我对@987654322@ + RefCount 的理解是,只要至少有一个订阅者,就会保持与源的连接。一旦最后一个订阅者断开连接,任何未来的订阅者都将重新启动与源的连接。
正如您在我的测试中看到的那样,第一次一切正常。但第二次,管道内的延迟 observable 会为每个新订阅者执行一次。
我可以通过调试器看到,对于第一组订阅者,obs._count(计算订阅者)在每次调用 Subscribe 时都会增加。但是对于第二组订阅者,它仍然是零。
为什么会发生这种情况,我可以做些什么来纠正我的管道?
【问题讨论】:
标签: c# .net system.reactive