我正在学习Rx,我想知道如何将重试结果打印到控制台,例如"重试#1","重试#2"等。我看到一些人使用.Dump
扩展方法,我找不到。
using System.Reactive.Concurrency;
using System.Reactive.Linq;
using System.Reactive.Threading.Tasks;
var test = new Test(new HttpClient());
var result = await test.GetAsync();
Console.WriteLine($"Result: {result}");
public sealed class Test
{
private readonly HttpClient _httpClient;
public Test(HttpClient httpClient)
{
_httpClient = httpClient;
}
public Task<string> GetAsync()
{
return Observable
.FromAsync(() => _httpClient.GetAsync("http://www.mocky.io/v2/5e307edf3200005d00858b49"))
.SubscribeOn(TaskPoolScheduler.Default)
.Retry(5)
.Timeout(TimeSpan.FromSeconds(5))
.Do(x => Console.WriteLine($"Is message successful? {x.IsSuccessStatusCode}"))
.SelectMany(async x =>
{
var response = await x.Content.ReadAsStringAsync();
return response;
})
.Catch<string, TimeoutException>(_ => Observable.Return("Timeout"))
.Catch<string, Exception>(ex => Observable.Return(ex.Message))
.ToTask();
}
}
下面是一个写重试的基本示例:
Observable
.Defer<int>(() =>
{
int counter = 0;
return
Observable
.Defer<int>(() =>
{
Console.WriteLine(counter++ > 0 ? $"Retry #{counter - 1}" : "First");
return Notification.CreateOnError<int>(new Exception()).ToObservable();
})
.Retry(5);
})
.Subscribe(
x => Console.WriteLine(x),
e => Console.WriteLine(e.Message));
这个输出:
First
Retry #1
Retry #2
Retry #3
Retry #4
Exception of type 'System.Exception' was thrown.
你正在重试的可观察对象应该包装在Observable.Defer
中,以防止重复值的可能性。每当我使用"外部"我还把它包在一个Observable.Defer
中。