如果我执行以下操作:
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
的"热"会产生这种情况:
From first: A0
From first: A1
From first: A2
From second: A3
From first: A3
使用 Publish() 和 Connect() 会使你的冷可观察变热。
var published = Observable
.Interval(...)
.Select(...)
.Publish();
var connectionSubscription = published.Connect();
var observerSubscription = published.Subscribe(...);
值得注意的是,一旦 Connect() 调用发生,序列就会很热。您可以在 Connect() 之前订阅,但请确保在某个阶段调用它,否则将永远不会观察到任何内容。Connect() 有一些替代品,例如 RefCount(),所以值得谷歌搜索。另外值得注意的是,Publish() 返回了一个提供 Connect() 调用的 IConnectableObservable。