Coverage Summary for Class: EmbeddedBlockWaitBudget (cloud.mindbox.mobile_sdk.embedded)
| Class |
Method, %
|
Branch, %
|
Line, %
|
Instruction, %
|
| EmbeddedBlockWaitBudget |
100%
(6/6)
|
100%
(4/4)
|
100%
(19/19)
|
100%
(104/104)
|
| EmbeddedBlockWaitBudget$1 |
100%
(1/1)
|
|
100%
(1/1)
|
100%
(2/2)
|
| EmbeddedBlockWaitBudget$expireRunnable$1$1 |
100%
(1/1)
|
|
100%
(1/1)
|
100%
(5/5)
|
| Total |
100%
(8/8)
|
100%
(4/4)
|
100%
(21/21)
|
100%
(111/111)
|
package cloud.mindbox.mobile_sdk.embedded
import android.os.Handler
import android.os.SystemClock
import cloud.mindbox.mobile_sdk.models.Milliseconds
import cloud.mindbox.mobile_sdk.utils.loggingRunCatching
internal class EmbeddedBlockWaitBudget(
private val duration: Milliseconds,
private val mainHandler: Handler,
private val now: () -> Long = { SystemClock.elapsedRealtime() },
private val onExpire: () -> Unit,
) {
private var consumedMs = 0L
private var resumedAt: Long? = null
private val expireRunnable = Runnable {
resumedAt = null
consumedMs = duration.interval
loggingRunCatching { onExpire() }
}
private val remainingMs: Long
get() = (duration.interval - consumedMs).coerceAtLeast(0L)
fun armIfNeeded() {
if (resumedAt != null) return
resumedAt = now()
mainHandler.postDelayed(expireRunnable, remainingMs)
}
fun pause() {
val startedAt = resumedAt ?: return
consumedMs += (now() - startedAt).coerceAtLeast(0L)
resumedAt = null
mainHandler.removeCallbacks(expireRunnable)
}
fun reset() {
pause()
consumedMs = 0L
}
}