Skip to content

Commit

Permalink
Optimize sensor list performance (#4853)
Browse files Browse the repository at this point in the history
- 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
  • Loading branch information
jpelgrom authored Nov 30, 2024
1 parent 51ae8b9 commit e7d5e4d
Showing 1 changed file with 10 additions and 3 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand Down Expand Up @@ -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()
}
}
}
}
Expand All @@ -67,7 +74,7 @@ class SensorSettingsViewModel @Inject constructor(
}
}

private suspend fun filterSensorsList() {
private suspend fun filterSensorsList() = withContext(Dispatchers.IO) {
val app = getApplication<Application>()
val managers = SensorReceiver.MANAGERS.sortedBy { app.getString(it.name) }
sensors = SensorReceiver.MANAGERS
Expand Down

0 comments on commit e7d5e4d

Please sign in to comment.