From e7d5e4d6c7ff3489a7804a26f4adc333de154906 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Joris=20Pelgr=C3=B6m?= Date: Sat, 30 Nov 2024 19:22:37 +0100 Subject: [PATCH] Optimize sensor list performance (#4853) - Prevent the list being filtered again every time something in the database is changed but the values don't change - Perform filtering of the sensors list on the IO thread instead of the main thread --- .../settings/sensor/SensorSettingsViewModel.kt | 13 ++++++++++--- 1 file changed, 10 insertions(+), 3 deletions(-) diff --git a/app/src/main/java/io/homeassistant/companion/android/settings/sensor/SensorSettingsViewModel.kt b/app/src/main/java/io/homeassistant/companion/android/settings/sensor/SensorSettingsViewModel.kt index 4586a25570f..da554d7b194 100644 --- a/app/src/main/java/io/homeassistant/companion/android/settings/sensor/SensorSettingsViewModel.kt +++ b/app/src/main/java/io/homeassistant/companion/android/settings/sensor/SensorSettingsViewModel.kt @@ -14,7 +14,9 @@ import io.homeassistant.companion.android.database.sensor.Sensor import io.homeassistant.companion.android.database.sensor.SensorDao import io.homeassistant.companion.android.sensors.SensorReceiver import javax.inject.Inject +import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch +import kotlinx.coroutines.withContext @HiltViewModel class SensorSettingsViewModel @Inject constructor( @@ -47,8 +49,13 @@ class SensorSettingsViewModel @Inject constructor( init { viewModelScope.launch { sensorDao.getAllFlow().collect { - sensorsList = it - filterSensorsList() + withContext(Dispatchers.IO) { + // Compare contents, because the worker typically pushes a DB update on + // sensor updates even when contents don't change + val different = sensorsList != it + sensorsList = it + if (different) filterSensorsList() + } } } } @@ -67,7 +74,7 @@ class SensorSettingsViewModel @Inject constructor( } } - private suspend fun filterSensorsList() { + private suspend fun filterSensorsList() = withContext(Dispatchers.IO) { val app = getApplication() val managers = SensorReceiver.MANAGERS.sortedBy { app.getString(it.name) } sensors = SensorReceiver.MANAGERS