Search code examples
xamarin.androidsystem.net.webexceptionpollyretry-logic

Polly show dialog after retry count reached


I'm using Polly to retry web service calls in case the call fails with WebException, because I want to make sure the method executed correctly before proceeding. However sometimes web methods still throw exception even after retrying several times and I don't want to retry forever. Can I use Polly to show some confirmation dialog, e.g. "Max retry count reached! Make sure connection is enabled and press retry." Then retry counter should reset to initial value and start again. Can I achieve this using only Polly or should I write my own logic? Ideas?


Solution

  • Polly has nothing in-built to manage dialog boxes as it is entirely agnostic to the context in which it is used. However, you can customise extra behaviour on retries with an onRetry delegate so you can hook a dialog box in there. Overall:

    • Use an outer RetryForever policy, and display the dialog box in the onRetry action configured on that policy.
      • If you want a way for the user to exit the RetryForever, a cancel action in the dialog could throw some other exception (which you trap with a try-catch round all the policies), to cause an exit.
    • Within the outer policy, use an inner Retry policy for however many tries you want to make without intervention.
      • Because this is a different policy instance from the retryforever, and has fixed retry count, the retry count will automatically start afresh each time it is executed.
    • Use PolicyWrap to wrap the two retry policies together.

    In pseudo-code:

    var retryUntilSucceedsOrUserCancels = Policy
        .Handle<WhateverException>()
        .RetryForever(onRetry: { /* show my dialog box*/ });
    var retryNTimesWithoutUserIntervention = Policy
        .Handle<WhateverException>()
        .Retry(n); // or whatever more sophisticated retry style you want
    var combined = retryUntilSucceedsOrUserCancels
        .Wrap(retryNTimesWithoutUserIntervention);
    
    combined.Execute( /* my work */ );
    

    Of course the use of the outer RetryForever() policy is just an option: you could also build the equivalent manually.