From a94c90e5aad37a9c6c3e9d3ff6f85c55f111988c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Joris=20Pelgr=C3=B6m?= Date: Fri, 20 Oct 2023 23:45:15 +0200 Subject: [PATCH] Improve camera tile add/remove event handling (#3954) - If there is already a camera tile with the ID of the tile in `onTileAddEvent` stored in the database, don't overwrite it with a new blank tile as the user configuration might be lost. - Run add/remove event code blocking to prevent the system immediately destroying the service and as a result cancelling the work to save tile data in the database. Without the blocking code I could semi-reliably get it to destroy the service within several milliseconds of adding/removing, often preventing the database code from running. --- .../companion/android/tiles/CameraTile.kt | 17 +++++++++-------- 1 file changed, 9 insertions(+), 8 deletions(-) diff --git a/wear/src/main/java/io/homeassistant/companion/android/tiles/CameraTile.kt b/wear/src/main/java/io/homeassistant/companion/android/tiles/CameraTile.kt index 8cc0b0671..4de307d62 100644 --- a/wear/src/main/java/io/homeassistant/companion/android/tiles/CameraTile.kt +++ b/wear/src/main/java/io/homeassistant/companion/android/tiles/CameraTile.kt @@ -28,7 +28,7 @@ import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Job import kotlinx.coroutines.cancel import kotlinx.coroutines.guava.future -import kotlinx.coroutines.launch +import kotlinx.coroutines.runBlocking import kotlinx.coroutines.withContext import okhttp3.OkHttpClient import okhttp3.Request @@ -185,16 +185,17 @@ class CameraTile : TileService() { builder.build() } - override fun onTileAddEvent(requestParams: EventBuilders.TileAddEvent) { - serviceScope.launch { - AppDatabase.getInstance(this@CameraTile) - .cameraTileDao() - .add(CameraTile(id = requestParams.tileId)) + override fun onTileAddEvent(requestParams: EventBuilders.TileAddEvent) = runBlocking { + withContext(Dispatchers.IO) { + val dao = AppDatabase.getInstance(this@CameraTile).cameraTileDao() + if (dao.get(requestParams.tileId) == null) { + dao.add(CameraTile(id = requestParams.tileId)) + } // else already existing, don't overwrite existing tile data } } - override fun onTileRemoveEvent(requestParams: EventBuilders.TileRemoveEvent) { - serviceScope.launch { + override fun onTileRemoveEvent(requestParams: EventBuilders.TileRemoveEvent) = runBlocking { + withContext(Dispatchers.IO) { AppDatabase.getInstance(this@CameraTile) .cameraTileDao() .delete(requestParams.tileId)