Git Product home page Git Product logo

retry's Introduction

Retry for Swift exceptions

Motivation

Sometimes, when a function throws an error, we want to repeat calling it, maybe with some delay. Here is example of such function:

// AVCaptureDevice
func lockForConfiguration() throws

This was the case for me when I needed to access the camera in one of my apps. I discovered that the camera may not be available right away due to multithreading or after using different camera app. And it makes sense to retry attempt to acquire the lock after a small delay.

do {
    // Try to acquire the lock of the system resource
    try resource.lockForConfiguration()
    // The lock acquired, perform operation with the system resource
    // ..
    // Release the lock
    resource.unlockForConfiguration()
}
catch {
    // Retry after delay
}

Solution

Solution is pretty simple: wrap do/catch block in a loop, that repeats for some number of retries and every n milliseconds, and breaks when the function succeeds. Because the solution fits well similar cases and overall for clear code I created retry function.

@discardableResult
public func retry<T>(times retryCount: UInt = 0,
                      withDelay delay: TimeInterval = 0.0,
                            _ closure: () throws -> T) rethrows -> T

The function executes the closure till it succeeds or exceeds number of retries. It rethrows the exception catched at the final attempt to execute the closure. And returns the closure result. Using Swift generics lets the retry function conveniently infer return type from the closure.

Usage

Here is the example of use for my case. This will repeat attempt to acquire the lock at least 11 times (initial attempt + 10 retries) with 100ms delay.

do {
    try retry(times: 10, withDelay: 0.1, {
        // Try to acquire the lock of the system resource.
        try resource.lockForConfiguration()
        // The lock acquired, perform operation with the system resource.
        // ..
        // Release the lock.
        resource.unlockForConfiguration()
    })
}
catch {
    // Handle error
}

This repository contains Swift 4.0 playground demonstrating the retry function. Future steps for this can be implementing simple exponential backoff algorithm for the delay.


2018 Dmytro Anokhin. MIT license.

retry's People

Contributors

dmytro-anokhin avatar

Stargazers

 avatar  avatar

Watchers

 avatar  avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.