DEV Community

Cover image for Automatic retry function with Kotlin flows
Tristan Elliott
Tristan Elliott

Posted on

Automatic retry function with Kotlin flows

Table of contents

  1. Short code example
  2. Why use this?

My app on the Google play store

Resources

  • Programming Android with Kotlin: Achieving Structured Concurrency with Coroutines. Chapter 10

Short code example

  • Here is the code that will allow you to make automatic retries on a flow:
    fun <T, R : Any> Flow<T>.mapWithRetry(
        action: suspend (T) -> R,
        predicate: suspend (R, attempt: Int) -> Boolean
    ) = map { data ->
        var attempt = 0L
        var shallRetry: Boolean
        var lastValue: R? = null
        do {
            val tr = action(data)
            shallRetry = predicate(tr, (++attempt).toInt())
            if (!shallRetry) lastValue = tr
        } while (shallRetry)
        return@map lastValue
    }

Enter fullscreen mode Exit fullscreen mode
  • Cold flow usage example:
twitchEmoteImpl.getChannelEmotes(
                oAuthToken,clientId,broadcasterId
            ).mapWithRetry(
                action={
                    // result is the result from getChannelEmotes()
                    // if you wanted to do any manipulation to the 
                    // request you would do it here
                        result -> result
                       },
                predicate = { result, attempt ->
                    val repeatResult = result is Response.Failure && attempt < 3
                    repeatResult
                }
            ).collect{
            // do what you would normally do once a flow is emitted 
            }

Enter fullscreen mode Exit fullscreen mode
  • result -> result represents the code not doing any sort of manipulation of the result emitted from the flow

Why use this?

  • There are times when the request fails and the best solution is to simply make another request. Instead of forcing your user to manually make another request. We can implement this function that will automatically make 3 requests if it fails. We will not inform the users of the extra requests. Instead they should only be informed after the 3 failed attempts
  • However, be aware that we should not do this on every failed request. On requests that fail due to authentication or no available network errors, we should avoid making multiple requests and simply inform the user of the failed request.

Conclusion

  • Thank you for taking the time out of your day to read this blog post of mine. If you have any questions or concerns please comment below or reach out to me on Twitter.

Top comments (0)