例如
var subject = new Subject<int>();
var test = subject.Scan(0, (x, y) => {
Console.WriteLine("scan");
return x + 1;
});
test.Subscribe(x => Console.WriteLine("subscribe1"));
//test.Subscribe(x => Console.WriteLine("subscribe2"));
Observable.Range(0, 1).Subscribe(subject);
Console.WriteLine("done");
Console.Read();
输出为
scan
subscribe1
done
但是如果你取消第二个订阅的注释,输出是
scan
subscribe1
scan
subscribe2
done
为什么扫描运行两次,我如何防止它?所以输出应该是
scan
subscribe1
subscribe2
done
我使用Subject来累积不同的Observables。然后我使用扫描方法来更新模型,然后我有不同的地方,我需要订阅模型更新。也许没有使用主题有更好的解决方案?
尝试使用Observable.Publish
获得IConnectableObservable<T>
。
var subject = new Subject<int>();
var test = subject
.Scan(0, (x, y) => {
Console.WriteLine("scan");
return x + 1;
})
.Publish();
test.Subscribe(x => Console.WriteLine("subscribe1"));
test.Subscribe(x => Console.WriteLine("subscribe2"));
test.Connect();
Observable.Range(0, 1).Subscribe(subject);
Console.WriteLine("done");
Console.Read();
输出:scan
subscribe1
subscribe2
done
Publish
将冷的Scan
观测对象转变为热观测对象,并在Connect
被调用时开始发光。
你看到的问题是Subject
是一个热可观察对象,而Scan
每次订阅它都会创建一个新的冷可观察对象。
尝试在被摄体前移动扫描
var subject = new Subject<int>();
subject.Subscribe(x => Console.WriteLine("subscribe1"));
subject.Subscribe(x => Console.WriteLine("subscribe2"));
Observable.Range(0, 1).Scan(0, (x, y) => {
Console.WriteLine("scan");
return x + 1;
}).Subscribe(subject);
Console.WriteLine("done");
Console.Read();
您也可以不使用Subject
:
var test = Observable.Range(0, 1).Scan(0, (x, y) => {
Console.WriteLine("scan");
return x + 1;
}).Publish();
test.Subscribe(x => Console.WriteLine("subscribe1"));
test.Subscribe(x => Console.WriteLine("subscribe2"));
test.Connect();
Console.WriteLine("done");
Console.Read();
热观测与冷观测