Skip to content

Commit 03600fa

Browse files
authored
[Fix] Cancel previous polling job upon restarting HWiNFO (#37)
1 parent 9b361e8 commit 03600fa

File tree

1 file changed

+18
-9
lines changed

1 file changed

+18
-9
lines changed

core/native/src/main/kotlin/br/com/firstsoft/core/os/hwinfo/HwInfoProcessManager.kt

Lines changed: 18 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,8 @@ package br.com.firstsoft.core.os.hwinfo
33
import br.com.firstsoft.core.os.resource.NativeResourceLoader
44
import kotlinx.coroutines.CoroutineScope
55
import kotlinx.coroutines.Dispatchers
6+
import kotlinx.coroutines.Job
7+
import kotlinx.coroutines.flow.cancellable
68
import kotlinx.coroutines.flow.collectLatest
79
import kotlinx.coroutines.flow.map
810
import kotlinx.coroutines.launch
@@ -14,6 +16,7 @@ object HwInfoProcessManager {
1416
private var process: Process? = null
1517
private const val MAX_RETRIES = 1
1618
private var currentRetries = 0
19+
private var pollingJob: Job? = null
1720

1821
init {
1922
currentRetries = 0
@@ -29,7 +32,8 @@ object HwInfoProcessManager {
2932
command("cmd.exe", "/c", file)
3033
}.start()
3134

32-
observeHwInfoPollingTime()
35+
pollingJob?.cancel()
36+
pollingJob = observeHwInfoPollingTime()
3337
}
3438

3539
fun stop() {
@@ -40,6 +44,11 @@ object HwInfoProcessManager {
4044
process = null
4145
}
4246

47+
private fun restart() {
48+
stop()
49+
start()
50+
}
51+
4352
private fun overwriteSettings() {
4453
try {
4554
val sourceSettings = NativeResourceLoader.load("/hwinfo/HWiNFO64.INI.src")
@@ -55,21 +64,21 @@ object HwInfoProcessManager {
5564

5665
HwInfoReader
5766
.currentData
67+
.cancellable()
5868
.map { it.header }
5969
.collectLatest {
6070
accumulator += 500
71+
if (accumulator < TimeUnit.SECONDS.toMillis(5)) return@collectLatest
6172

62-
if (accumulator >= TimeUnit.SECONDS.toMillis(5)) {
63-
accumulator = 0
64-
65-
if (lastPollTime != it.pollTime) {
73+
accumulator = 0
74+
when {
75+
lastPollTime != it.pollTime -> {
6676
lastPollTime = it.pollTime
6777
currentRetries = 0
68-
} else if (currentRetries < MAX_RETRIES) {
78+
}
79+
lastPollTime == it.pollTime && currentRetries < MAX_RETRIES -> {
6980
currentRetries++
70-
stop()
71-
start()
72-
return@collectLatest
81+
restart()
7382
}
7483
}
7584
}

0 commit comments

Comments
 (0)