Add throttling/debouncing on Wear OS for registry updates (#3517)

This commit is contained in:
Joris Pelgröm 2023-05-13 05:00:56 +02:00 committed by GitHub
parent 7d6f11af4f
commit d81913b7ea
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
2 changed files with 24 additions and 3 deletions

View file

@ -0,0 +1,20 @@
package io.homeassistant.companion.android.util
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.conflate
import kotlinx.coroutines.flow.transform
/**
* Emit the first value from a Flow, and then after the period has passed the last item emitted
* by the Flow during that period (if different). This ensures throttling/debouncing but also
* always receiving the first and last item of the Flow.
*
* From https://github.com/Kotlin/kotlinx.coroutines/issues/1446#issuecomment-1198103541
*/
fun <T> Flow<T>.throttleLatest(delayMillis: Long): Flow<T> = this
.conflate()
.transform {
emit(it)
delay(delayMillis)
}

View file

@ -29,6 +29,7 @@ import io.homeassistant.companion.android.database.wear.getAll
import io.homeassistant.companion.android.database.wear.getAllFlow
import io.homeassistant.companion.android.sensors.SensorReceiver
import io.homeassistant.companion.android.util.RegistriesDataHandler
import io.homeassistant.companion.android.util.throttleLatest
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.async
import kotlinx.coroutines.flow.Flow
@ -217,7 +218,7 @@ class MainViewModel @Inject constructor(
if (!homePresenter.isConnected() || isFavoritesOnly) {
return
}
homePresenter.getAreaRegistryUpdates()?.collect {
homePresenter.getAreaRegistryUpdates()?.throttleLatest(1000)?.collect {
areaRegistry = homePresenter.getAreaRegistry()
areas.clear()
areaRegistry?.let {
@ -231,7 +232,7 @@ class MainViewModel @Inject constructor(
if (!homePresenter.isConnected() || isFavoritesOnly) {
return
}
homePresenter.getDeviceRegistryUpdates()?.collect {
homePresenter.getDeviceRegistryUpdates()?.throttleLatest(1000)?.collect {
deviceRegistry = homePresenter.getDeviceRegistry()
updateEntityDomains()
}
@ -241,7 +242,7 @@ class MainViewModel @Inject constructor(
if (!homePresenter.isConnected()) {
return
}
homePresenter.getEntityRegistryUpdates()?.collect {
homePresenter.getEntityRegistryUpdates()?.throttleLatest(1000)?.collect {
entityRegistry = homePresenter.getEntityRegistry()
_supportedEntities.value = getSupportedEntities()
updateEntityDomains()