7

Backoff and Retry Strategy using Flows in Android

 3 years ago
source link: https://proandroiddev.com/backoff-and-retry-strategy-using-flows-in-android-ed2478d23492
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Backoff and Retry Strategy using Flows in Android

Image for post
Image for post

You might come across a situation while developing an app where you’d want to retry a certain request when an Exception occurs without user’s intervention.

A pragmatic example would be a case of an IO Exception. Consider this use case. You want to fetch a list of dogs from the server, however, you get an IO exception due to a network issue.

Now you can either trigger another request right away or wait for sometime (backoff) and retry. In this article we will explore the backoff method.

Image for post
Image for post
In this case, The first the network request return IOException first 2 attempts and in the third attempt Result.Success is returned.

Setting up ViewModel

getDogImages() is a function that throw an IOException randomly, mocking a network response. In a real app it should trigger a network request.

Now this is where the magic happens. We use a special operators called .retryWhen which has two parameters cause and attempt . cause is a throwable (returned from getDogImages() flow) and attempt is the number of attempt number.

Now whenever getDogImages() throws an exception, We check if the Exception was an IOException and check if the attempt number is less than three.

If both conditions are satisfied, We emit a ResultWrapper.NetworkError(..)
to notify the UI about the Error and backoff for a time delay of 2000 * (attempt + 1) milliseconds. With each new attempt we backoff for more time than last time when retrying.

If the getDogImages() functionthrows Exception three times , We stop retrying and an emit ResultWrapper.NetworkError(“Retries Expired!”, null) , followed by return@retryWhen false.

Make sure you add a catch {} block to handle the above Exceptions

Setting up the View

Now in the View, collect the above flow an update UI accordingly.

And That’s It

You have successfully implemented a Back Off Strategy with retry using flows. You can extrapolate this idea to any other Exception where you’d want to retry a request without user’s intervention smartly.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK