有没有热的'相当于Observable.Interval

时间:2015-04-20 15:18:20

标签: c# system.reactive

如果我执行以下操作:

var obs = 
    Observable
    .Interval(TimeSpan.FromSeconds(1))
    .Select(x => "A" + x.ToString());

obs
.Subscribe(x => Console.WriteLine("From first: " + x.ToString()));

Observable
.Timer(TimeSpan.FromSeconds(3))
.SelectMany(_ => obs)
.Subscribe(x => Console.WriteLine("From second: " + x.ToString()));

我会在4秒后得到这个:

From first:  A0
From first:  A1
From first:  A2
From second: A0
From first:  A3

是否有一个等同于Observable.Interval的'Hot'会产生这个:

From first:  A0
From first:  A1
From first:  A2
From second: A3
From first:  A3

1 个答案:

答案 0 :(得分:4)

使用Publish()和Connect()会让你的冷可观察性变得很热。

var published = Observable
   .Interval(...)
   .Select(...)
   .Publish();

var connectionSubscription = published.Connect();
var observerSubscription = published.Subscribe(...);

值得注意的是,一旦Connect()调用发生,序列就会变热。您可以在Connect()之前订阅,但请确保在某个阶段调用它,否则将无法观察到任何内容。 Connect()有一些替代方案,例如RefCount()所以值得谷歌。另外值得注意的是,Publish()返回一个提供Connect()调用的IConnectableObservable。