-
Notifications
You must be signed in to change notification settings - Fork 1
/
TotalPlaytimeCounter.kt
56 lines (50 loc) · 1.38 KB
/
TotalPlaytimeCounter.kt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
/*
* Copyright (c) SRG SSR. All rights reserved.
* License information is available from the LICENSE file.
*/
package ch.srgssr.pillarbox.core.business.tracker
import kotlin.time.Duration
import kotlin.time.Duration.Companion.milliseconds
/**
* Total playtime counter.
*
* @param timeProvider A callback invoked whenever the current time is needed.
*/
class TotalPlaytimeCounter internal constructor(
private val timeProvider: () -> Long,
) {
private var totalPlayTime: Duration = Duration.ZERO
private var lastPlayTime = 0L
constructor() : this(
timeProvider = { System.currentTimeMillis() },
)
/**
* Play
* Calling twice play after sometime will compute totalPlaytime
*/
fun play() {
pause()
lastPlayTime = timeProvider()
}
/**
* Get total play time
*
* @return if paused totalPlayTime else totalPlayTime + delta from last play
*/
fun getTotalPlayTime(): Duration {
return if (lastPlayTime <= 0L) {
totalPlayTime
} else {
totalPlayTime + (timeProvider() - lastPlayTime).milliseconds
}
}
/**
* Pause total play time tracking and compute total playtime.
*/
fun pause() {
if (lastPlayTime > 0L) {
totalPlayTime += (timeProvider() - lastPlayTime).milliseconds
lastPlayTime = 0L
}
}
}