Skip to content

Commit 60ab1f1

Browse files
committed
Fix: Stop InputDeviceMonitor on dispose
1 parent 7205d92 commit 60ab1f1

File tree

2 files changed

+32
-20
lines changed

2 files changed

+32
-20
lines changed
File renamed without changes.

AdaptiveJetStream/jetstream/src/main/java/com/google/jetstream/presentation/components/feature/InputDeviceType.kt

Lines changed: 32 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@ import android.os.Handler
2222
import android.os.HandlerThread
2323
import android.view.InputDevice
2424
import androidx.compose.runtime.Composable
25+
import androidx.compose.runtime.DisposableEffect
2526
import androidx.compose.runtime.State
2627
import androidx.compose.runtime.getValue
2728
import androidx.compose.runtime.remember
@@ -51,7 +52,7 @@ enum class InputDeviceType {
5152

5253
class InputDeviceMonitor(
5354
private var inputManager: InputManager,
54-
onInputDeviceUpdated: (List<InputDeviceType>) -> Unit
55+
private val onInputDeviceUpdated: (List<InputDeviceType>) -> Unit
5556
) : HandlerThread("InputDeviceMonitor") {
5657

5758
private lateinit var handler: Handler
@@ -67,31 +68,36 @@ class InputDeviceMonitor(
6768
override fun onInputDeviceChanged(deviceId: Int) {
6869
updateDeviceList()
6970
}
71+
}
7072

71-
private fun updateDeviceList() {
72-
val updatedList = inputManager.inputDeviceIds
73-
.map { deviceId ->
74-
inputManager.getInputDevice(deviceId)
75-
}
76-
.filterNotNull()
77-
.filter { device ->
78-
device.isEnabled && !device.isVirtual
79-
}
80-
.map { device ->
81-
device.deviceType()
82-
}
83-
.flatten()
84-
.toSet()
85-
.toList()
86-
87-
onInputDeviceUpdated(updatedList)
88-
}
73+
private fun updateDeviceList() {
74+
val updatedList = inputManager.inputDeviceIds
75+
.map { deviceId ->
76+
inputManager.getInputDevice(deviceId)
77+
}
78+
.filterNotNull()
79+
.filter { device ->
80+
device.isEnabled && !device.isVirtual
81+
}
82+
.map { device ->
83+
device.deviceType()
84+
}
85+
.flatten()
86+
.toSet()
87+
.toList()
88+
onInputDeviceUpdated(updatedList)
8989
}
9090

9191
override fun onLooperPrepared() {
9292
super.onLooperPrepared()
9393
handler = Handler(looper)
9494
inputManager.registerInputDeviceListener(listener, handler)
95+
updateDeviceList()
96+
}
97+
98+
override fun quitSafely(): Boolean {
99+
inputManager.unregisterInputDeviceListener(listener)
100+
return super.quitSafely()
95101
}
96102
}
97103

@@ -108,8 +114,14 @@ internal fun rememberInputDeviceMonitor(
108114
InputDeviceMonitor(
109115
inputManager = inputManager,
110116
onInputDeviceUpdated = onInputDeviceUpdated
111-
).also { monitor ->
117+
)
118+
}.also { monitor ->
119+
DisposableEffect(monitor) {
112120
monitor.start()
121+
122+
onDispose {
123+
monitor.quitSafely()
124+
}
113125
}
114126
}
115127
}

0 commit comments

Comments
 (0)