Skip to content

Commit

Permalink
adding logic to add notInitialized as it would prevent state to first…
Browse files Browse the repository at this point in the history
… resume.
  • Loading branch information
RishavG96 committed Apr 8, 2024
1 parent 2a56592 commit 268f9bb
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 25 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -18,17 +18,16 @@ class RepeatingTimer {

var timeInterval: TimeInterval = 0

private var suspensionCount = 0

private init() { }

init(timeInterval: TimeInterval) {
self.timeInterval = timeInterval
}

private lazy var timer: DispatchSourceTimer = {
private lazy var timer: DispatchSourceTimer = { [weak self] in
let t = DispatchSource.makeTimerSource()
t.schedule(deadline: .now() + self.timeInterval, repeating: self.timeInterval)
guard let checkedSelf = self else { return t }
t.schedule(deadline: .now() + (checkedSelf.timeInterval), repeating: checkedSelf.timeInterval)
t.setEventHandler(handler: { [weak self] in
self?.eventHandler?()
})
Expand All @@ -38,11 +37,12 @@ class RepeatingTimer {
var eventHandler: (() -> Void)?

private enum State {
case notInitialized
case suspended
case resumed
}

private var state: Atomic<State> = Atomic(.suspended)
private var state: Atomic<State> = Clickstream.timerCrashFixFlag ? Atomic(.notInitialized) : Atomic(.suspended)

deinit {
timer.setEventHandler {}
Expand All @@ -55,37 +55,32 @@ class RepeatingTimer {
eventHandler = nil
}

// decrements an internal suspension count.
func resume() {
if state.value == .resumed {
return
}
suspensionCount -= 1
state.mutate { state in
state = .resumed
}
if Clickstream.timerCrashFixFlag {
if suspensionCount > 0 {
self.timer.resume()
if state.value == .resumed || state.value == .notInitialized {
return
}
} else {
timer.resume()
if state.value == .resumed {
return
}
}
state.mutate { state in
state = .resumed
}
timer.resume()

}

// increments an internal suspension count.
func suspend() {
if state.value == .suspended {
return
}
suspensionCount += 1
state.mutate { state in
state = .suspended
}
if Clickstream.timerCrashFixFlag {
if suspensionCount > 0 {
timer.suspend()
}
} else {
timer.suspend()
}
timer.suspend()
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,11 @@ final class DefaultKeepAliveServiceWithSafeTimer: KeepAliveService {

func start(with subscriber: @escaping KeepAliveCallback) {
stop()
timer?.resume()
if Clickstream.timerCrashFixFlag {
timer?.suspend()
} else {
timer?.resume()
}
self.subscriber = subscriber
}

Expand Down Expand Up @@ -114,6 +118,10 @@ final class DefaultKeepAliveServiceWithSafeTimer: KeepAliveService {
}

func stop() {
timer?.suspend()
if Clickstream.timerCrashFixFlag {
timer?.resume()
} else {
timer?.suspend()
}
}
}

0 comments on commit 268f9bb

Please sign in to comment.