Move startingTimer to a dedicated object

This commit is contained in:
sim 2024-10-29 15:06:07 +00:00
parent 1cd2340b6c
commit dfeec5cc43

View File

@ -32,20 +32,7 @@ class SSEListener(val context: Context) : EventSourceListener() {
override fun onOpen(eventSource: EventSource, response: Response) { override fun onOpen(eventSource: EventSource, response: Response) {
FailureHandler.newEventSource(context, eventSource) FailureHandler.newEventSource(context, eventSource)
val timer: TimerTask? = if ( StartingTimer.scheduleNewTimer(context, eventSource)
!AppCompanion.bufferedResponseChecked.get() &&
!AppCompanion.booting.getAndSet(false)
) {
Timer().schedule(45_000L /* 45secs */) {
if (FailureHandler.newFail(context, eventSource)) {
StartService.stopService()
NoStartNotification(context).showSingle()
}
}
} else {
null
}
startingTimer.getAndSet(timer)?.cancel()
WakeLock.instance?.release() WakeLock.instance?.release()
try { try {
Log.d(TAG, "onOpen: " + response.code) Log.d(TAG, "onOpen: " + response.code)
@ -62,7 +49,7 @@ class SSEListener(val context: Context) : EventSourceListener() {
when (type) { when (type) {
"start" -> { "start" -> {
AppCompanion.started.set(true) AppCompanion.started.set(true)
startingTimer.getAndSet(null)?.cancel() StartingTimer.stop()
AppCompanion.bufferedResponseChecked.set(true) AppCompanion.bufferedResponseChecked.set(true)
NoStartNotification(context).delete() NoStartNotification(context).delete()
} }
@ -173,16 +160,37 @@ class SSEListener(val context: Context) : EventSourceListener() {
* timeout is high enough. * timeout is high enough.
*/ */
private fun clearDebugVars() { private fun clearDebugVars() {
startingTimer.getAndSet(null)?.cancel() StartingTimer.stop()
AppCompanion.started.set(false) AppCompanion.started.set(false)
AppCompanion.pinged.set(false) AppCompanion.pinged.set(false)
} }
companion object {
/** /**
* Timer to stop the service if we don't receive the `start` event within 45 seconds. * Timer to stop the service if we don't receive the `start` event within 45 seconds.
* Used to check if there is a reverse proxy buffering responses. * Used to check if there is a reverse proxy buffering responses.
*/ */
private object StartingTimer {
private var startingTimer: AtomicReference<TimerTask?> = AtomicReference(null) private var startingTimer: AtomicReference<TimerTask?> = AtomicReference(null)
fun scheduleNewTimer(context: Context, eventSource: EventSource) {
val timer: TimerTask? = if (
!AppCompanion.bufferedResponseChecked.get() &&
!AppCompanion.booting.getAndSet(false)
) {
Timer().schedule(45_000L /* 45secs */) {
if (FailureHandler.newFail(context, eventSource)) {
StartService.stopService()
NoStartNotification(context).showSingle()
}
}
} else {
null
}
startingTimer.getAndSet(timer)?.cancel()
}
fun stop() {
startingTimer.getAndSet(null)?.cancel()
}
} }
} }