Advertisement
Guest User

Untitled

a guest
Sep 20th, 2019
84
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.85 KB | None | 0 0
  1. import RxSwift
  2.  
  3. /**
  4. Specifies how observable sequence will be repeated in case of an error
  5. - Immediate: Will be immediatelly repeated specified number of times
  6. - Delayed: Will be repeated after specified delay specified number of times
  7. - ExponentialDelayed: Will be repeated specified number of times.
  8. Delay will be incremented by multiplier after each iteration (multiplier = 0.5 means 50% increment)
  9. - CustomTimerDelayed: Will be repeated specified number of times. Delay will be calculated by custom closure
  10. */
  11. public enum RepeatBehavior {
  12. case immediate (maxCount: UInt)
  13. case delayed (maxCount: UInt, time: Double)
  14. case exponentialDelayed (maxCount: UInt, initial: Double, multiplier: Double)
  15. case customTimerDelayed (maxCount: UInt, delayCalculator: (UInt) -> DispatchTimeInterval)
  16. }
  17.  
  18. extension RepeatBehavior {
  19. /**
  20. Extracts maxCount and calculates delay for current RepeatBehavior
  21. - parameter currentAttempt: Number of current attempt
  22. - returns: Tuple with maxCount and calculated delay for provided attempt
  23. */
  24. func calculateConditions(_ currentRepetition: UInt) -> (maxCount: UInt, delay: DispatchTimeInterval) {
  25. switch self {
  26. case .immediate(let max):
  27. // if Immediate, return 0.0 as delay
  28. return (maxCount: max, delay: .never)
  29. case .delayed(let max, let time):
  30. // return specified delay
  31. return (maxCount: max, delay: .milliseconds(Int(time * 1000)))
  32. case .exponentialDelayed(let max, let initial, let multiplier):
  33. // if it's first attempt, simply use initial delay, otherwise calculate delay
  34. let delay = currentRepetition == 1 ? initial : initial * pow(1 + multiplier, Double(currentRepetition - 1))
  35. return (maxCount: max, delay: .milliseconds(Int(delay * 1000)))
  36. case .customTimerDelayed(let max, let delayCalculator):
  37. // calculate delay using provided calculator
  38. return (maxCount: max, delay: delayCalculator(currentRepetition))
  39. }
  40. }
  41. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement