更新时间:2023-11-21 20:04:10
您不想将 async
方法传递给 Subscribe
,因为这将创建 async void
方法.尽力避免 async void
.
You don't want to pass an async
method to Subscribe
, because that will create an async void
method. Do your best to avoid async void
.
在您的情况下,我想想您想要对序列的每个元素调用 async
方法,然后缓存所有结果.在这种情况下,请使用 SelectMany
调用每个元素的 async
方法,并使用 Replay
进行缓存(加上 Connect
使球滚动):
In your case, I think what you want is to call the async
method for each element of the sequence and then cache all the results. In that case, use SelectMany
to call the async
method for each element, and Replay
to cache (plus a Connect
to get the ball rolling):
public class Consumer
{
private readonly Service _service = new Service();
public IObservable<string> Trigger()
{
var connectible = Observable.Timer(TimeSpan.FromMilliseconds(100))
.SelectMany(_ => RunAsync())
.Replay();
connectible.Connect();
return connectible;
}
public Task<string> RunAsync()
{
return _service.DoAsync();
}
}
我更改了 Results
属性,改为从 Trigger
方法返回,我认为这更有意义,因此现在的测试如下:
I changed the Results
property to be returned from the Trigger
method instead, which I think makes more sense, so the test now looks like:
[Test]
public async Task Test()
{
var sut = new Consumer();
var results = sut.Trigger();
var result = await results.FirstAsync();
}