Write an Rx “RetryAfter” extension method

前端 未结 6 924
花落未央
花落未央 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:42

    Here's the one I came up with.

    Didn't want to concatenate the items of individual retries into one sequence, but emit the source sequence as a whole on each retry - so the operator returns an IObservable>. If this is not desired, it can simply be Switch()ed back into one sequence.

    (Background: in my use case the source is a hot hot sequence, which I GroupByUntilan item appears that closes the group. If this item is lost between two retries, the group is never closed, resulting in a memory leak. Having a sequence of sequences allows for grouping on the inner sequences only (or exception handling or ...).)

    /// 
    /// Repeats  in individual windows, with  time in between.
    /// 
    public static IObservable> RetryAfter(this IObservable source, TimeSpan interval, IScheduler scheduler = null)
    {
        if (scheduler == null) scheduler = Scheduler.Default;
        return Observable.Create>(observer =>
        {
            return scheduler.Schedule(self =>
            {
                observer.OnNext(Observable.Create(innerObserver =>
                {
                    return source.Subscribe(
                        innerObserver.OnNext,
                        ex => { innerObserver.OnError(ex); scheduler.Schedule(interval, self); },
                        () => { innerObserver.OnCompleted(); scheduler.Schedule(interval, self); });
                }));
            });
        });
    }
    

提交回复
热议问题