Write an Rx “RetryAfter” extension method

前端 未结 6 940
花落未央
花落未央 2020-11-27 16:00

In the book IntroToRx the author suggest to write a \"smart\" retry for I/O which retry an I/O request, like a network request, after a period of time.

Here is the e

6条回答
  •  醉酒成梦
    2020-11-27 16:58

    Based on Markus' answer I wrote the following:

    public static class ObservableExtensions
    {
        private static IObservable BackOffAndRetry(
            this IObservable source,
            Func strategy,
            Func retryOnError,
            int attempt)
        {
            return Observable
                .Defer(() =>
                {
                    var delay = attempt == 0 ? TimeSpan.Zero : strategy(attempt);
                    var s = delay == TimeSpan.Zero ? source : source.DelaySubscription(delay);
    
                    return s
                        .Catch(e =>
                        {
                            if (retryOnError(attempt, e))
                            {
                                return source.BackOffAndRetry(strategy, retryOnError, attempt + 1);
                            }
                            return Observable.Throw(e);
                        });
                });
        }
    
        public static IObservable BackOffAndRetry(
            this IObservable source,
            Func strategy,
            Func retryOnError)
        {
            return source.BackOffAndRetry(strategy, retryOnError, 0);
        }
    }
    

    I like it more because

    • it doesn't modify attempts but uses recursion.
    • It doesn't use retries but passes the number of attempts to retryOnError

提交回复
热议问题