How to Manually Retry a Call Using Kotlin Flow?

First implementation: without retry

Your view model will look more or less like this:

  • I created sealed classes to represent each screen state (you can read a little more about this approach here ).
  • I exposed a Flow that fetch the store list and wrap it in a UiState class.

However, this approach doesn't provide us with an easy way to restart the flow if something went wrong on the first try. The Flow framework has a way to set up a retry behaviour but this happens automatically, not by the user command. You can see more about the built-in approach here.

Giving our Flow the power to restart

I spent some time thinking about how to do it. Read some articles and reached on the following implementation:

The final implementation 

  • I created an instance of RetryTrigger and passed it as the first argument on the retryable flow creation method.
  • The main flow was wrapped in a retryable flow. I decided to pass this flow inside a lambda. I could even make this method inline, but these are implementation decisions, and is up to you to decide what fits better to your project.
  • Now there is a tryAgain() method that calls retryTrigger.retry(). This method should be called when the user presses the “try again” button on the error screen.