Haven't you wished for `try` to sometimes try a little harder? Meet `retry`

Related tags

Utility Retry
Overview

Retry

Version License Platform

Example

Haven't you wished for try to sometimes try a little harder? Meet retry

To run the example project, clone the repo, and run pod install from the Example directory first.

The full test suite shows a variety of use cases.

Synchronous retry

NB: The sync retry is not good for use on the main thread (because it will block it if you're having delays, etc). For the main thread it's better considering retryAsync (more info below).

Default parameters - retry three times without any delay:

retry {
  ... do some throwing work ...
}

Catching the last error, and adding a defer block after all tries have finished - will keep trying maximum 10 times. You can use either of the final blocks or both:

retry (max: 10) {
  ... do some throwing work ...
}
.finalCatch {lastError in
  print("This simply won't happen. Failed with: \(lastError)")
}
.finalDefer {
  print("Finished trying")
}

Add 2 second delay between the retries:

retry (max: 5, retryStrategy: .delay(seconds: 2.0)) {
  ... do some throwing work ...
}

Implement any custom delay logic (below is multiplying the waiting time after each try):

retry (max: 5, retryStrategy: .custom {count, lastDelay in return (lastDelay ?? 1.0) * 2.0} ) {
  ... do some throwing work ...
}

Limit the number of retries based on any custom logic - if you return nil from your custom strategy, retry will stop trying:

retry (max: 5, retryStrategy: .custom {count,_ in return count > 3 ? nil : 0} ) {
  ... do some throwing work ...
}

Asynchronous retry

The syntax for retryAsync is exactly the same as for retry. The difference in behavior is if the first try fails retryAsync keeps trying asynchronously instead of blocking the current thread.

Installation

Retry is available through CocoaPods. To install it, simply add the following line to your Podfile:

pod "Retry"

Retry is also available through Swift Package Manager. To install, add https://github.com/icanzilb/Retry.git to your package manifest.

Since Retry is a swift3 library, you got to add this piece of code to your project's Podfile, to update your targets' swift language version:

post_install do |installer|
    installer.pods_project.targets.each do |target|
        target.build_configurations.each do |config|
            config.build_settings['SWIFT_VERSION'] = '3.0'
            config.build_settings['MACOSX_DEPLOYMENT_TARGET'] = '10.10'
        end
    end
end

Author

Marin Todorov, 2016-present

Inspired by the retry operator in https://github.com/RxSwiftCommunity/RxSwiftExt

License

Retry is available under the MIT license. See the LICENSE file for more info.

You might also like...
Extensions that allow you to work with optionals

RxOptionals Sometimes it happens that you need to bind to several optional binders or to an optional method (for example, when using weak). To do this

Headline News Widget for Pock.You can display the articles fetched by rss.
Headline News Widget for Pock.You can display the articles fetched by rss.

Headline News Widget for Pock This is a headline news widget plugin for Pock You can display the articles fetched by rss. Demo In the demo video, the

Generates a random photo after you click the button

Swift Random Photo Generator Generates a random photo after you click the button! Things you need to do 📖 clone this repository git clone https://git

ALO sync allows you to sync resources form an ALO endpoint to your macOS file system.
ALO sync allows you to sync resources form an ALO endpoint to your macOS file system.

ALO sync allows you to sync resources form an ALO endpoint to your macOS file system. Prerequisites macOS 11 No support for search* No suppor

LibAuthentication will simplify your code when if you want to use FaceID/TouchID in your tweaks.

LibAuthentication will simplify your code when if you want to use FaceID/TouchID in your tweaks.

📡 Helping you own NotificationCenter in Swift!

Notificationz 📡 Helping you own NotificationCenter Highlights Keep Your Naming Conventions: This library gives you convenient access to NotificationC

A powerful app that lets you play Blackjack on Mac for free 🎰

Blackjack A powerful application for Mac to play the classic casino game, Blackjack. This app was created so I can understand the basics of Swift. Mad

Weather and forecasts for humans. Information you can act on.

Tropos Weather and forecasts for humans. Information you can act on. Most weather apps throw a lot of information at you but that doesn't answer the q

A way to represent what you’re sharing.
A way to represent what you’re sharing.

About This project provides a preview of items being shared via UIActivityViewController. Example: // standard activity view controller let vc = UIAct

Comments
  • Fix async retry called from a non-main thread

    Fix async retry called from a non-main thread

    Async retry assumed that it is always called from a main thread. While it is often a case, it could be potentially called from any thread and finalXXXX can also be called from other thread than main now. This fix synchronizes async call with a private queue that is also used to schedule retries. In addition, working on lastError inside running was dangerous.

    Since now, async tests do not know when "-end" is appended to the output. I removed those expectations keeping in mind that verifying "-end" order was never crucial for async operations.

    opened by polac24 6
  • Added support for Carthage

    Added support for Carthage

    What does this PR do?

    Added support for Carthage.

    Why are we doing this? Any context or related work?

    Some people (such as me) need to use Carthage to avoid compiling third-party libraries over and over again. The existing project has no valid shared framework schemes. And the deployment version is iOS 10.0, which is different from the deployment version of iOS 9.0 for the library. The PR fixes these problems.

    Major changes

    • Updated README.md.
    • Updated the Retry's version of example project to latest. (0.6.2)
    • Downgraded the deployment target version of example project from iOS 10.0 to iOS 9.0.
    • Share Retry scheme only, cancel share Retry-Example scheme.

    Where should a reviewer start?

    mkdir -p /tmp/RetryCarthage
    cd /tmp/RetryCarthage
    echo 'github "VincentSit/Retry" "master"' > Cartfile
    carthage update
    
    // Or combined.
    mkdir -p /tmp/RetryCarthage && cd /tmp/RetryCarthage && echo 'github "VincentSit/Retry" "master"' > Cartfile && carthage update
    

    Screenshots

    ➜  ~ mkdir -p /tmp/RetryCarthage && cd /tmp/RetryCarthage && echo 'github "VincentSit/Retry" "master"' > Cartfile && carthage update
    *** Fetching Retry
    *** Checking out Retry at "8d31ce7e7e114f668bde2492d1d06729ec7b92ca"
    *** xcodebuild output can be found in /var/folders/k_/qmb6n50s0n70zgzj_008xwpc0000gn/T/carthage-xcodebuild.sZ6l0U.log
    *** Building scheme "Retry" in Retry.xcworkspace
    ➜  RetryCarthage ls Carthage/Build/iOS/
    503C3B60-B9A7-33E6-A9B3-389E9256F12F.bcsymbolmap Retry.framework
    B42B0559-5F35-3B4C-ADB8-D389613399EA.bcsymbolmap Retry.framework.dSYM
    

    Others

    If you decide to accept and merge this PR, to make Carthage work, you may need to release a new version, since the current version does not include these changes. Otherwise the user needs to specify the branch in Cartfile to work, like github "icanzilb/Retry" "master".

    opened by VincentSit 2
Releases(0.6.3)
Owner
Marin Todorov
Experienced on  platforms. Author of "Modern Concurrency in Swift", "Combine: Asynchronous Programming with Swift", and others.
Marin Todorov
What if you could give your wallpapers, a little touch? On the fly, of course

Amēlija On the fly preferences. Features Custom Blurs for your LockScreen. Custom Blurs for your HomeScreen. Blur Types Epic (Gaussian). Dark. Light.

null 9 Dec 2, 2022
Lock a terminal command to the efficiency or performance cores on a big.LITTLE ARM processor

CPU-Lock Lock a terminal command to the efficiency or performance cores on a big.LITTLE ARM processor (Designed for Apple Silicon). Usage Download the

BitesPotatoBacks 0 Aug 11, 2022
A little beautifier tool for xcodebuild

xcbeautify xcbeautify is a little beautifier tool for xcodebuild. Similar to xcpretty, but faster. Features 2x faster than xcpretty. Human-friendly an

Tuist 650 Dec 30, 2022
The Objective-C block utilities you always wish you had.

BlocksKit Blocks in C and Objective-C are downright magical. They make coding easier and potentially quicker, not to mention faster on the front end w

BlocksKit 6.9k Dec 28, 2022
Pavel Surový 0 Jan 1, 2022
Differific is a diffing tool that helps you compare Hashable objects using the Paul Heckel's diffing algorithm

Differific is a diffing tool that helps you compare Hashable objects using the Paul Heckel's diffing algorithm. Creating a chan

Christoffer Winterkvist 127 Jun 3, 2022
Ethereum Wallet Toolkit for iOS - You can implement an Ethereum wallet without a server and blockchain knowledge.

Introduction EtherWalletKit is an Ethereum Wallet Toolkit for iOS. I hope cryptocurrency and decentralized token economy become more widely adapted. H

Sung Woo Chang 136 Dec 25, 2022
LifetimeTracker can surface retain cycle / memory issues right as you develop your application

LifetimeTracker Bar style Circular style LifetimeTracker can surface retain cycle / memory issues right as you develop your application, and it will s

Krzysztof Zabłocki 2.8k Jan 4, 2023
WhatsNewKit enables you to easily showcase your awesome new app features.

WhatsNewKit enables you to easily showcase your awesome new app features. It's designed from the ground up to be fully customized to your needs. Featu

Sven Tiigi 2.8k Jan 3, 2023