Nowadays, most mobile and desktop applications depend on external services for their optimal operations. Whether it is for the consumption of data or sending data via a REST API, or the download of data from a third-party source. When you build an application that depends on these external services, the communication between your application and these services will surely not be 100% present and robust all the time. Several scenarios can cause a connection break between your application and the external service. Such as: loss of connection, or an inappropriate response from the service in question. This could include other scenarios.

This kind of situation cannot be avoided by the developer however, they can be treated with elegance and in a resilient way. This article is about using Polly to handle these issues when consuming a REST API in a Xamarin.Forms application.

What is Polly?

As written in this ReadMe on Github, “ Polly is a .NET resilience and transient-fault-handling library that allows developers to express policies such as Retry, Circuit Breaker, Timeout, Bulkhead Isolation, and Fallback in a fluent and thread-safe manner. ”

Making Request to REST APIs With Polly and Xamarin Forms

The source code in this demo is derived from a Xamarin Forms app, but is absolutely not tied to Xamarin Forms and could be used in your c# projects. In fact this post primarily focuses on Polly and not Xamarin Forms. The app is a currency converter made in Xamarin Forms. You can find it here on Github. It leverages Polly’s Policies to consume data from a currency converter API in a resilient way.

The goal of this exercise is to use the currency conversion API via this application and retry our request each time we encounter an exception of the type HttpRequestException (That is, when our application will encounter a problem during this request). Thanks to Polly, we can define this Policy easily. We can also add several other criteria to customize this policy in our own way. Let’s dive into the demo.

First, you need to add Polly into your application. Do this via nuget in the following way. In your nuget packet manager, write this.

Install-Package Polly

async Task<HttpResponseMessage> QueryCurrencyServiceWithRetryPolicy(Func<Task<HttpResponseMessage>> action) { int numberOfTimesToRetry = 7; int retryMultiple = 2; //Handle HttpRequestException when it occures var response = await Policy.Handle<HttpRequestException>(ex => { Debug.WriteLine("Request failed due to connectivity issues."); return true; }) //wait for a given number of seconds which increases after each retry .WaitAndRetryAsync(numberOfTimesToRetry, retryCount => TimeSpan.FromSeconds(retryCount * retryMultiple)) //After the retry, Execute the appropriate set of instructions .ExecuteAsync(async () => await action()); //Return the response message gotten from the http client call. return response; } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 async Task < HttpResponseMessage > QueryCurrencyServiceWithRetryPolicy ( Func < Task < HttpResponseMessage >> action ) { int numberOfTimesToRetry = 7 ; int retryMultiple = 2 ; //Handle HttpRequestException when it occures var response = await Policy . Handle < HttpRequestException > ( ex = > { Debug . WriteLine ( "Request failed due to connectivity issues." ) ; return true ; } ) //wait for a given number of seconds which increases after each retry . WaitAndRetryAsync ( numberOfTimesToRetry , retryCount = > TimeSpan . FromSeconds ( retryCount * retryMultiple ) ) //After the retry, Execute the appropriate set of instructions . ExecuteAsync ( async ( ) = > await action ( ) ) ; //Return the response message gotten from the http client call. return response ; }

This piece of code defines the Policy and takes a function to execute during this Policy.

//Now let's call our retry policy each time we want to query the API var response = await QueryCurrencyServiceWithRetryPolicy(() => _httpClient.GetAsync(ALL_CURRENCIES_URL)); 1 2 //Now let's call our retry policy each time we want to query the API var response = await QueryCurrencyServiceWithRetryPolicy ( ( ) = > _httpClient . GetAsync ( ALL_CURRENCIES_URL ) ) ;

Note that “ALL_CURRENCIES_URL” is a constant that contains the URL to the Currency REST API to download the currencies. And the variable “_httpClient” makes a “GET” on the API. This could be replaced by any URL to which you want to make a GET request.

Conclusion

With that, we have a simple implementation of a piece of code that retries a request to an API for a specific number of times. While increasing the waiting time with each new request made. This can be very useful when making requests to an API in a mobile application.

You could be interested by this article about making a snack bar in your Xamarin Forms Application

Like this: Like Loading...

Follow me on social media and stay updated