可观察.生成延迟结果
本文关键字:延迟 结果 观察 | 更新日期: 2023-09-27 18:30:24
以下代码将结果延迟 2 秒。我想要的是立即返回结果,但每 2 秒启动一个新的可观察量。我错过了什么?
输出:
**The current output is:**
05: 1. Run
07 Result: 1
07: 2. Run
09 Result: 2
09: 3. Run
11 Result: 3
**Desired output is:**
05: 1. Run
05 Result: 1
07: 2. Run
07 Result: 2
09: 3. Run
09 Result: 3
法典:
var sources = Enumerable.Range(1, 8).Select(i =>
{
Console.WriteLine("{0}: {1}. Run", DateTimeOffset.Now.ToString("ss"), i);
return Observable.Return(i, CurrentThreadScheduler.Instance);
});
Observable.Generate(sources.GetEnumerator(), e => e.MoveNext(), e => e, e => e.Current, e => TimeSpan.FromMilliseconds(2000), ThreadPoolScheduler.Instance)
.Merge()
.Timestamp()
.Do(r =>
{
Console.WriteLine("{0} Result: {1}{2}", r.Timestamp.ToString("ss"), r.Value, Environment.NewLine);
},
ex =>
{
Console.WriteLine(ex.ToString());
},
() =>
{
Console.WriteLine("Completed");
})
.Subscribe();
怎么样:
Observable.Interval(TimeSpan.Zero, TimeSpan.FromSeconds(2.0))
.SelectMany(_ => GenerateAnObservable())
.Subscribe(/* ... */);
如何用这个替换您当前的Observable.Generate
:
Observable
.Generate(
0,
i => true,
i => i + 1,
i => i,
i => TimeSpan.FromMilliseconds(i == 0 ? 0 : 2000),
ThreadPoolScheduler.Instance)
.Zip(sources, (g, s) => s)
我得到了这个结果:
41: 1. Run
41 Result: 1
43: 2. Run
43 Result: 2
45: 3. Run
45 Result: 3
47: 4. Run
47 Result: 4
49: 5. Run
49 Result: 5
51: 6. Run
51 Result: 6
53: 7. Run
53 Result: 7
55: 8. Run
55 Result: 8
Completed