【问题标题】:Print out Retry(5) attempts in Rx在 Rx 中打印出 Retry(5) 次尝试
【发布时间】:2023-01-23 07:22:38
【问题描述】:

我正在学习 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();
    }
}

【问题讨论】:

  • 我知道目标是学习 Rx 但是只是为了记录: 我更喜欢 Polly。
  • .Dump()来自LINQPad。我现在在 LP 中完成大部分编码。

标签: c# .net system.reactive


【解决方案1】:

这是写出重试的基本示例:

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 中。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-01-18
    • 2020-09-21
    • 2013-06-15
    • 1970-01-01
    • 1970-01-01
    • 2021-07-01
    • 1970-01-01
    • 2016-03-18
    相关资源
    最近更新 更多