Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import RxSwift
- /**
- Specifies how observable sequence will be repeated in case of an error
- - Immediate: Will be immediatelly repeated specified number of times
- - Delayed: Will be repeated after specified delay specified number of times
- - ExponentialDelayed: Will be repeated specified number of times.
- Delay will be incremented by multiplier after each iteration (multiplier = 0.5 means 50% increment)
- - CustomTimerDelayed: Will be repeated specified number of times. Delay will be calculated by custom closure
- */
- public enum RepeatBehavior {
- case immediate (maxCount: UInt)
- case delayed (maxCount: UInt, time: Double)
- case exponentialDelayed (maxCount: UInt, initial: Double, multiplier: Double)
- case customTimerDelayed (maxCount: UInt, delayCalculator: (UInt) -> DispatchTimeInterval)
- }
- extension RepeatBehavior {
- /**
- Extracts maxCount and calculates delay for current RepeatBehavior
- - parameter currentAttempt: Number of current attempt
- - returns: Tuple with maxCount and calculated delay for provided attempt
- */
- func calculateConditions(_ currentRepetition: UInt) -> (maxCount: UInt, delay: DispatchTimeInterval) {
- switch self {
- case .immediate(let max):
- // if Immediate, return 0.0 as delay
- return (maxCount: max, delay: .never)
- case .delayed(let max, let time):
- // return specified delay
- return (maxCount: max, delay: .milliseconds(Int(time * 1000)))
- case .exponentialDelayed(let max, let initial, let multiplier):
- // if it's first attempt, simply use initial delay, otherwise calculate delay
- let delay = currentRepetition == 1 ? initial : initial * pow(1 + multiplier, Double(currentRepetition - 1))
- return (maxCount: max, delay: .milliseconds(Int(delay * 1000)))
- case .customTimerDelayed(let max, let delayCalculator):
- // calculate delay using provided calculator
- return (maxCount: max, delay: delayCalculator(currentRepetition))
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement