Modern Apps git

← Modern-Apps.git

general: update DatabaseViewModel

Commit
267d03f3b2d59ee62f31343867d503662d9d3134
Author
Vayun Mathur <[email protected]>
When
2026-03-17 08:16 UTC (8 months ago)
Parents
e33f949

Diff

clock/src/main/java/com/vayunmathur/clock/ui/AlarmPage.kt
diff --git a/clock/src/main/java/com/vayunmathur/clock/ui/AlarmPage.kt b/clock/src/main/java/com/vayunmathur/clock/ui/AlarmPage.ktindex fb4b4c39a8..a8f019677f 100644--- a/clock/src/main/java/com/vayunmathur/clock/ui/AlarmPage.kt+++ b/clock/src/main/java/com/vayunmathur/clock/ui/AlarmPage.kt@@ -89,7 +89,7 @@ fun AlarmCard(                 )                 Row {                     Switch(checked = alarm.enabled, onCheckedChange = {-                        viewModel.upsert(alarm.copy(enabled = it))+                        viewModel.upsertAsync(alarm.copy(enabled = it))                     })                     IconButton({                         viewModel.delete(alarm)@@ -104,7 +104,7 @@ fun AlarmCard(                         checked = alarm.days and (1 shl idx) != 0,                         onCheckedChange = {                             val newDays = if (alarm.days and (1 shl idx) != 0) alarm.days and (1 shl idx).inv() else alarm.days or (1 shl idx)-                            viewModel.upsert(alarm.copy(days = newDays))+                            viewModel.upsertAsync(alarm.copy(days = newDays))                         }                     ) {                         Text(day.toString())
clock/src/main/java/com/vayunmathur/clock/ui/TimerPage.kt
diff --git a/clock/src/main/java/com/vayunmathur/clock/ui/TimerPage.kt b/clock/src/main/java/com/vayunmathur/clock/ui/TimerPage.ktindex 2a502bf974..71297bdcd6 100644--- a/clock/src/main/java/com/vayunmathur/clock/ui/TimerPage.kt+++ b/clock/src/main/java/com/vayunmathur/clock/ui/TimerPage.kt@@ -5,9 +5,7 @@ import android.app.NotificationManager import android.app.PendingIntent import android.content.Context import android.content.Intent-import android.os.Build import androidx.compose.foundation.Canvas-import androidx.compose.foundation.background import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column@@ -21,8 +19,6 @@ import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.width import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.items-import androidx.compose.foundation.shape.CircleShape-import androidx.compose.material3.Button import androidx.compose.material3.Card import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.FilledTonalButton@@ -34,9 +30,7 @@ import androidx.compose.material3.Text import androidx.compose.material3.TopAppBar import androidx.compose.runtime.Composable import androidx.compose.runtime.collectAsState-import androidx.compose.runtime.derivedStateOf import androidx.compose.runtime.getValue-import androidx.compose.runtime.remember import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color@@ -55,7 +49,6 @@ import com.vayunmathur.library.ui.IconAdd import com.vayunmathur.library.ui.IconDelete import com.vayunmathur.library.ui.IconPause import com.vayunmathur.library.ui.IconPlay-import com.vayunmathur.library.ui.ListPage import com.vayunmathur.library.util.BottomNavBar import com.vayunmathur.library.util.DatabaseViewModel import com.vayunmathur.library.util.nowState@@ -157,7 +150,7 @@ fun TimerCard(timer: Timer, now: Instant, viewModel: DatabaseViewModel) {                     FilledTonalButton(onClick = {                         val newLength = timer.remainingLength + 1.minutes                         val updatedTimer = timer.copy(remainingLength = newLength)-                        viewModel.upsert(updatedTimer)+                        viewModel.upsertAsync(updatedTimer)                          // If it's already running, update the notification immediately                         if (timer.isRunning) {@@ -173,11 +166,11 @@ fun TimerCard(timer: Timer, now: Instant, viewModel: DatabaseViewModel) {                     FilledTonalButton(                         onClick = {                             if (timer.isRunning) {-                                viewModel.upsert(timer.stopped())+                                viewModel.upsertAsync(timer.stopped())                                 sendTimerNotification(context, timer, false)                             } else {                                 val startedTimer = timer.started()-                                viewModel.upsert(startedTimer)+                                viewModel.upsertAsync(startedTimer)                                 // We pass the current realRemainingTime to the service                                 sendTimerNotification(context, startedTimer, true)                             }
clock/src/main/java/com/vayunmathur/clock/ui/dialog/NewTimerDialog.kt
diff --git a/clock/src/main/java/com/vayunmathur/clock/ui/dialog/NewTimerDialog.kt b/clock/src/main/java/com/vayunmathur/clock/ui/dialog/NewTimerDialog.ktindex 519ad79919..11875490d2 100644--- a/clock/src/main/java/com/vayunmathur/clock/ui/dialog/NewTimerDialog.kt+++ b/clock/src/main/java/com/vayunmathur/clock/ui/dialog/NewTimerDialog.kt@@ -9,7 +9,6 @@ import androidx.compose.material3.OutlinedTextField import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue-import androidx.compose.runtime.mutableIntStateOf import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue@@ -47,7 +46,7 @@ fun NewTimerDialog(backStack: NavBackStack<Route>, viewModel: DatabaseViewModel)                     }                     Button({                         val timer = Timer(true, name, Clock.System.now(), minutes!!.minutes + seconds!!.seconds, minutes!!.minutes + seconds!!.seconds)-                        viewModel.upsert(timer) {+                        viewModel.upsertAsync(timer) {                             sendTimerNotification(context, timer.copy(id = it), true)                         }                         backStack.pop()
findfamily/src/main/java/com/vayunmathur/findfamily/LocationTrackingService.kt
diff --git a/findfamily/src/main/java/com/vayunmathur/findfamily/LocationTrackingService.kt b/findfamily/src/main/java/com/vayunmathur/findfamily/LocationTrackingService.ktindex 10e69d4fbd..c40d0b80ba 100644--- a/findfamily/src/main/java/com/vayunmathur/findfamily/LocationTrackingService.kt+++ b/findfamily/src/main/java/com/vayunmathur/findfamily/LocationTrackingService.kt@@ -102,14 +102,14 @@ class LocationTrackingService : Service() {                     val inWaypoint = waypoints.find { havershine(it.coord, lastLocation.coord) < it.range }                     if(inWaypoint != null) {                         if(inWaypoint.name != user.locationName)-                            viewModel.upsert(user.copy(locationName = inWaypoint.name, lastLocationChangeTime = lastLocation.timestamp))+                            viewModel.upsertAsync(user.copy(locationName = inWaypoint.name, lastLocationChangeTime = lastLocation.timestamp))                     } else {                         val address =                             fetchAddress(lastLocation.coord.lat, lastLocation.coord.lon)?.let {                                 it.featureName ?: it.thoroughfare                             } ?: "Unknown Location"                         if(user.locationName != address)-                            viewModel.upsert(user.copy(locationName = address, lastLocationChangeTime = lastLocation.timestamp))+                            viewModel.upsertAsync(user.copy(locationName = address, lastLocationChangeTime = lastLocation.timestamp))                     }                 }             }
findfamily/src/main/java/com/vayunmathur/findfamily/Networking.kt
diff --git a/findfamily/src/main/java/com/vayunmathur/findfamily/Networking.kt b/findfamily/src/main/java/com/vayunmathur/findfamily/Networking.ktindex 6f9c7168c1..69f6956af5 100644--- a/findfamily/src/main/java/com/vayunmathur/findfamily/Networking.kt+++ b/findfamily/src/main/java/com/vayunmathur/findfamily/Networking.kt@@ -143,7 +143,7 @@ object Networking {         } else {             getKey(user.id)?.also {                 val keyString = Base64.encode(it.encodeToByteArray(RSA.PublicKey.Format.PEM))-                viewModel.upsert(user.copy(encryptionKey = keyString))+                viewModel.upsertAsync(user.copy(encryptionKey = keyString))             }         } ?: return false         return makeRequest("/api/location/publish", encryptLocation(location, user.id, key)) ?: false
findfamily/src/main/java/com/vayunmathur/findfamily/ui/MapView.kt
diff --git a/findfamily/src/main/java/com/vayunmathur/findfamily/ui/MapView.kt b/findfamily/src/main/java/com/vayunmathur/findfamily/ui/MapView.ktindex 47ce7b4e7e..6be44e394d 100644--- a/findfamily/src/main/java/com/vayunmathur/findfamily/ui/MapView.kt+++ b/findfamily/src/main/java/com/vayunmathur/findfamily/ui/MapView.kt@@ -92,7 +92,7 @@ fun MapView(         delay(1000)         if (users.isEmpty()) {             withContext(Dispatchers.IO) {-                viewModel.upsert(+                viewModel.upsertAsync(                     User(                         "Me",                         null,
findfamily/src/main/java/com/vayunmathur/findfamily/ui/UserPage.kt
diff --git a/findfamily/src/main/java/com/vayunmathur/findfamily/ui/UserPage.kt b/findfamily/src/main/java/com/vayunmathur/findfamily/ui/UserPage.ktindex 48be95f40d..1f10710065 100644--- a/findfamily/src/main/java/com/vayunmathur/findfamily/ui/UserPage.kt+++ b/findfamily/src/main/java/com/vayunmathur/findfamily/ui/UserPage.kt@@ -72,7 +72,7 @@ fun UserPage(platform: Platform, backStack: NavBackStack<Route>, viewModel: Data     var historicalPosition by remember { mutableStateOf<Position?>(null) }      val requestPickContact1 = platform.requestPickContact { name, photo ->-        viewModel.upsert(selectedUser.copy(name = name, photo = photo))+        viewModel.upsertAsync(selectedUser.copy(name = name, photo = photo))     }      Scaffold(topBar = { TopAppBar({}, navigationIcon = { IconNavigation(backStack) }, actions = {@@ -102,7 +102,7 @@ fun UserPage(platform: Platform, backStack: NavBackStack<Route>, viewModel: Data                             Checkbox(                                 selectedUser.sendingEnabled,                                 { send ->-                                    viewModel.upsert(selectedUser.copy(sendingEnabled = send))+                                    viewModel.upsertAsync(selectedUser.copy(sendingEnabled = send))                                 })                         }                     }
findfamily/src/main/java/com/vayunmathur/findfamily/ui/WaypointEditPage.kt
diff --git a/findfamily/src/main/java/com/vayunmathur/findfamily/ui/WaypointEditPage.kt b/findfamily/src/main/java/com/vayunmathur/findfamily/ui/WaypointEditPage.ktindex ab24f56765..4b5e83a660 100644--- a/findfamily/src/main/java/com/vayunmathur/findfamily/ui/WaypointEditPage.kt+++ b/findfamily/src/main/java/com/vayunmathur/findfamily/ui/WaypointEditPage.kt@@ -40,7 +40,7 @@ fun WaypointEditPage(backStack: NavBackStack<Route>, viewModel: DatabaseViewMode     Scaffold(floatingActionButton = {         FloatingActionButton({             if(range.toDoubleOrNull() == null || name.isBlank()) return@FloatingActionButton-            viewModel.upsert(waypoint.copy(name = name, range = range.toDouble(), coord = coord))+            viewModel.upsertAsync(waypoint.copy(name = name, range = range.toDouble(), coord = coord))             backStack.pop()         }) {             IconSave()
findfamily/src/main/java/com/vayunmathur/findfamily/ui/dialog/AddLinkDialog.kt
diff --git a/findfamily/src/main/java/com/vayunmathur/findfamily/ui/dialog/AddLinkDialog.kt b/findfamily/src/main/java/com/vayunmathur/findfamily/ui/dialog/AddLinkDialog.ktindex 793b47a3a9..7199396063 100644--- a/findfamily/src/main/java/com/vayunmathur/findfamily/ui/dialog/AddLinkDialog.kt+++ b/findfamily/src/main/java/com/vayunmathur/findfamily/ui/dialog/AddLinkDialog.kt@@ -67,7 +67,7 @@ fun AddLinkDialog(backStack: NavBackStack<Route>, viewModel: DatabaseViewModel,                                 Base64.encode(keypair.publicKey.encodeToByteArray(RSA.PublicKey.Format.PEM)),                                 Clock.System.now() + options[expiryTime]!!                             )-                            viewModel.upsert(newLink)+                            viewModel.upsertAsync(newLink)                             backStack.pop()                         }                     },
findfamily/src/main/java/com/vayunmathur/findfamily/ui/dialog/AddPersonDialog.kt
diff --git a/findfamily/src/main/java/com/vayunmathur/findfamily/ui/dialog/AddPersonDialog.kt b/findfamily/src/main/java/com/vayunmathur/findfamily/ui/dialog/AddPersonDialog.ktindex 91445b2323..ce39d9664e 100644--- a/findfamily/src/main/java/com/vayunmathur/findfamily/ui/dialog/AddPersonDialog.kt+++ b/findfamily/src/main/java/com/vayunmathur/findfamily/ui/dialog/AddPersonDialog.kt@@ -105,7 +105,7 @@ fun AddPersonDialog(backStack: NavBackStack<Route>, viewModel: DatabaseViewModel                             null,                             userid.decodeBase26()                         )-                        viewModel.upsert(userToAdd, {+                        viewModel.upsertAsync(userToAdd, {                             backStack.pop()                         })                     },
gradle/libs.versions.toml
diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.tomlindex 60c33d2759..ffd51ddf42 100644--- a/gradle/libs.versions.toml+++ b/gradle/libs.versions.toml@@ -8,7 +8,7 @@ ksp = "2.3.4" coreKtx = "1.17.0" lifecycleRuntimeKtx = "2.10.0" lifecycleViewmodel = "2.10.0"-litertlmAndroid = "0.8.0"+litertlmAndroid = "0.9.0-alpha06" workRuntimeKtx = "2.11.1" datastorePreferences = "1.2.0" 
library/src/main/java/com/vayunmathur/library/util/Navigation.kt
diff --git a/library/src/main/java/com/vayunmathur/library/util/Navigation.kt b/library/src/main/java/com/vayunmathur/library/util/Navigation.ktindex eb3e480336..bc5955eb9b 100644--- a/library/src/main/java/com/vayunmathur/library/util/Navigation.kt+++ b/library/src/main/java/com/vayunmathur/library/util/Navigation.kt@@ -46,7 +46,7 @@ class NavResultRegistry {  // The Composable helper (The "ResultEffect" you saw) @Composable-inline fun <reified T> ResultEffect(key: String, crossinline onResult: (T) -> Unit) {+inline fun <reified T> ResultEffect(key: String, crossinline onResult: suspend (T) -> Unit) {     val registry = LocalNavResultRegistry.current     LaunchedEffect(registry) {         registry.results.collect { (k, result) ->
library/src/main/java/com/vayunmathur/library/util/RoomViewModel.kt
diff --git a/library/src/main/java/com/vayunmathur/library/util/RoomViewModel.kt b/library/src/main/java/com/vayunmathur/library/util/RoomViewModel.ktindex 53a5f7f35a..9e32d50f1d 100644--- a/library/src/main/java/com/vayunmathur/library/util/RoomViewModel.kt+++ b/library/src/main/java/com/vayunmathur/library/util/RoomViewModel.kt@@ -28,14 +28,11 @@ import androidx.room.Upsert import androidx.room.migration.Migration import androidx.sqlite.db.SimpleSQLiteQuery import androidx.sqlite.db.SupportSQLiteQuery-import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.channels.awaitClose import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.SharingStarted import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.callbackFlow-import kotlinx.coroutines.flow.filter-import kotlinx.coroutines.flow.map import kotlinx.coroutines.flow.stateIn import kotlinx.coroutines.launch import kotlinx.coroutines.runBlocking@@ -48,36 +45,13 @@ import kotlin.time.Duration import kotlin.time.Duration.Companion.milliseconds import kotlin.time.Instant -class DaoInterface<T: DatabaseItem>(val dao: TrueDao<T>, val viewModelScope: CoroutineScope) {-    fun delete(t: T, andThen: (Int) -> Unit = {}) {-        viewModelScope.launch {-            val id = dao.delete(t)-            andThen(id)-        }-    }--    fun upsert(t: T, andThen: (Long) -> Unit = {}) {-        viewModelScope.launch {-            val id = dao.upsert(t)-            andThen(id)-        }-    }--    fun upsertAll(t: List<T>) {-        viewModelScope.launch {-            dao.upsertAll(t)-        }-    }-}  class DatabaseViewModel(val database: RoomDatabase, vararg daos: Pair<KClass<*>, TrueDao<*>>, val matchingDao: MatchingDao? = null) : ViewModel() {-    val daoMap = daos.associate {-        it.first to DaoInterface(it.second, viewModelScope)-    }+    val daos = daos.associate { it.first to it.second }      inline fun <reified A: DatabaseItem, reified B: DatabaseItem> addPairs(pairs: List<Pair<A, B>>) {-        val classAIndex = daoMap.keys.indexOf(A::class)-        val classBIndex = daoMap.keys.indexOf(B::class)+        val classAIndex = daos.keys.indexOf(A::class)+        val classBIndex = daos.keys.indexOf(B::class)         val type = min(classAIndex, classBIndex) + 100 * max(classAIndex, classBIndex)         val pairs = if(classAIndex < classBIndex) pairs else pairs.map { it.second to it.first }         viewModelScope.launch {@@ -92,8 +66,8 @@ class DatabaseViewModel(val database: RoomDatabase, vararg daos: Pair<KClass<*>,     }      suspend inline fun <reified A: DatabaseItem, reified B: DatabaseItem> getMatches(a: Long): List<Long> {-        val classAIndex = daoMap.keys.indexOf(A::class)-        val classBIndex = daoMap.keys.indexOf(B::class)+        val classAIndex = daos.keys.indexOf(A::class)+        val classBIndex = daos.keys.indexOf(B::class)         val type = min(classAIndex, classBIndex) + 100 * max(classAIndex, classBIndex)         val ids = if(classAIndex < classBIndex) matchingDao!!.getFromLeft(a, type) else matchingDao!!.getFromRight(a, type)         return ids@@ -103,8 +77,8 @@ class DatabaseViewModel(val database: RoomDatabase, vararg daos: Pair<KClass<*>,      @Composable     inline fun <reified A: DatabaseItem, reified B: DatabaseItem> getMatchesState(a: Long): State<List<Long>> {-        val classAIndex = daoMap.keys.indexOf(A::class)-        val classBIndex = daoMap.keys.indexOf(B::class)+        val classAIndex = daos.keys.indexOf(A::class)+        val classBIndex = daos.keys.indexOf(B::class)         val type = min(classAIndex, classBIndex) + 100 * max(classAIndex, classBIndex)          val matches by matchesStateFlow!!.collectAsState()@@ -114,10 +88,10 @@ class DatabaseViewModel(val database: RoomDatabase, vararg daos: Pair<KClass<*>,     }  -    inline fun <reified E : DatabaseItem> getDaoInterface(): DaoInterface<E> {-        val daoInterface = daoMap[E::class] ?: throw Exception("No DAO registered for ${E::class.simpleName}")+    inline fun <reified E : DatabaseItem> getDao(): TrueDao<E> {+        val dao = daos[E::class] ?: throw Exception("No DAO registered for ${E::class.simpleName}")         @Suppress("UNCHECKED_CAST")-        return daoInterface as DaoInterface<E>+        return dao as TrueDao<E>     }      @Composable@@ -134,22 +108,11 @@ class DatabaseViewModel(val database: RoomDatabase, vararg daos: Pair<KClass<*>,         return derived     } -    inline fun <reified E: DatabaseItem> upsertAll(items: List<E>) {-        getDaoInterface<E>().upsertAll(items)-    }--    inline fun <reified E: DatabaseItem> replaceAll(items: List<E>) {-        database.openHelper.writableDatabase.delete(E::class.simpleName!!, null, null)-        upsertAll(items)-    }-     @Composable     inline fun <reified E : DatabaseItem> getEditable(         initialId: Long,         crossinline default: () -> E? = { null }     ): MutableState<E> {-        val daoInterface = getDaoInterface<E>()-         // 1. Track the current ID. If it's 0, it will be updated after the first upsert.         var currentId by remember { mutableLongStateOf(initialId) } @@ -177,7 +140,7 @@ class DatabaseViewModel(val database: RoomDatabase, vararg daos: Pair<KClass<*>,                         localState.value = newValue                          // Push to database-                        daoInterface.upsert(newValue) { newId ->+                        upsertAsync(newValue) { newId ->                             // If this was a new item (ID 0), update our pointer to the new ID                             if (currentId == 0L) {                                 currentId = newId@@ -212,22 +175,45 @@ class DatabaseViewModel(val database: RoomDatabase, vararg daos: Pair<KClass<*>,                      // 3. Clean up the observer when the UI stops listening                     awaitClose { database.invalidationTracker.removeObserver(observer) }-                }.stateIn(viewModelScope, SharingStarted.Eagerly, getAll())+                }.stateIn(viewModelScope, SharingStarted.Eagerly, getAll<E>())             } as StateFlow<List<E>>         }     } -    suspend inline fun <reified E : DatabaseItem> getAll(): List<E> {-        val tableName = E::class.simpleName!!-        return getDaoInterface<E>().dao.observeRaw(SimpleSQLiteQuery("SELECT * FROM $tableName"))+    inline fun <reified E: DatabaseItem> upsertAll(items: List<E>) {+        viewModelScope.launch {+            getDao<E>().upsertAll(items)+        }+    }++    inline fun <reified E: DatabaseItem> replaceAll(items: List<E>) {+        database.openHelper.writableDatabase.delete(E::class.simpleName!!, null, null)+        upsertAll(items)+    }++    suspend inline fun <reified E: DatabaseItem> getAll(): List<E> {+        return getDao<E>().getAll<E>()+    }++    suspend inline fun <reified E: DatabaseItem> get(id: Long): E {+        return getDao<E>().get<E>(id)     } -    inline fun <reified E: DatabaseItem> upsert(t: E, noinline andThen: (Long) -> Unit = {}) {-        getDaoInterface<E>().upsert(t, andThen)+    inline fun <reified E: DatabaseItem> upsertAsync(t: E, noinline andThen: (Long) -> Unit = {}) {+        viewModelScope.launch {+            val id = getDao<E>().upsert(t)+            andThen(id)+        }     } -    inline fun <reified E: DatabaseItem> delete(t: E, noinline andThen: (Int) -> Unit = {}) {-        getDaoInterface<E>().delete(t, andThen)+    suspend inline fun <reified E: DatabaseItem> upsert(t: E): Long {+        return getDao<E>().upsert(t)+    }++    inline fun <reified E: DatabaseItem> delete(t: E) {+        viewModelScope.launch {+            getDao<E>().delete(t)+        }     } } @@ -277,7 +263,19 @@ interface TrueDao<T: DatabaseItem> {     @Upsert     suspend fun upsertAll(t: List<T>)     @RawQuery-    suspend fun observeRaw(query: SupportSQLiteQuery): List<T>+    suspend fun observeRawList(query: SupportSQLiteQuery): List<T>+    @RawQuery+    suspend fun observeRaw(query: SupportSQLiteQuery): T+}++suspend inline fun <reified E : DatabaseItem> TrueDao<E>.getAll(): List<E> {+    val tableName = E::class.simpleName!!+    return observeRawList(SimpleSQLiteQuery("SELECT * FROM $tableName"))+}++suspend inline fun <reified E : DatabaseItem> TrueDao<E>.get(id: Long): E {+    val tableName = E::class.simpleName!!+    return observeRaw(SimpleSQLiteQuery("SELECT * FROM $tableName WHERE id = $id")) }  val databases: MutableMap<KClass<*>, RoomDatabase> = mutableMapOf()
music/src/main/java/com/vayunmathur/music/ui/AlbumScreen.kt
diff --git a/music/src/main/java/com/vayunmathur/music/ui/AlbumScreen.kt b/music/src/main/java/com/vayunmathur/music/ui/AlbumScreen.ktindex 1e214b5d5e..41ffa50e6e 100644--- a/music/src/main/java/com/vayunmathur/music/ui/AlbumScreen.kt+++ b/music/src/main/java/com/vayunmathur/music/ui/AlbumScreen.kt@@ -53,17 +53,7 @@ fun AlbumScreen(backStack: NavBackStack<Route>, viewModel: DatabaseViewModel) {             }, searchEnabled = true, bottomBar = {                 PlayingBottomBar(playbackManager, backStack)             }, fab = {-                FloatingActionButton({-                    coroutineScope.launch {-                        val allSongs = viewModel.getAll<Music>()-                        val toPlayIndex = Random.nextInt(allSongs.size)-                        playbackManager.playSong(allSongs, toPlayIndex)-                        if (!playbackManager.shuffleMode.value)-                            playbackManager.toggleShuffle()-                    }-                }) {-                    Icon(painterResource(R.drawable.ic_shuffle), null)-                }+                ShufflePlayFab(viewModel, playbackManager)             })         }     }
music/src/main/java/com/vayunmathur/music/ui/ArtistScreen.kt
diff --git a/music/src/main/java/com/vayunmathur/music/ui/ArtistScreen.kt b/music/src/main/java/com/vayunmathur/music/ui/ArtistScreen.ktindex 21b86498e2..f7b3409031 100644--- a/music/src/main/java/com/vayunmathur/music/ui/ArtistScreen.kt+++ b/music/src/main/java/com/vayunmathur/music/ui/ArtistScreen.kt@@ -63,17 +63,7 @@ fun ArtistScreen(backStack: NavBackStack<Route>, viewModel: DatabaseViewModel) {             }, searchEnabled = true, bottomBar = {                 PlayingBottomBar(playbackManager, backStack)             }, fab = {-                FloatingActionButton({-                    coroutineScope.launch {-                        val allSongs = viewModel.getAll<Music>()-                        val toPlayIndex = Random.nextInt(allSongs.size)-                        playbackManager.playSong(allSongs, toPlayIndex)-                        if (!playbackManager.shuffleMode.value)-                            playbackManager.toggleShuffle()-                    }-                }) {-                    Icon(painterResource(R.drawable.ic_shuffle), null)-                }+                ShufflePlayFab(viewModel, playbackManager)             })         }     }
music/src/main/java/com/vayunmathur/music/ui/HomeScreen.kt
diff --git a/music/src/main/java/com/vayunmathur/music/ui/HomeScreen.kt b/music/src/main/java/com/vayunmathur/music/ui/HomeScreen.ktindex 169b55849d..f1fce28aca 100644--- a/music/src/main/java/com/vayunmathur/music/ui/HomeScreen.kt+++ b/music/src/main/java/com/vayunmathur/music/ui/HomeScreen.kt@@ -53,8 +53,6 @@ fun HomeScreen(backStack: NavBackStack<Route>, viewModel: DatabaseViewModel) {     val context = LocalContext.current     val playbackManager = remember { PlaybackManager.getInstance(context) } -    val coroutineScope = rememberCoroutineScope()-     Scaffold(bottomBar = {         BottomNavBar(backStack, listOf(             BottomBarItem("Home", Route.Home, R.drawable.baseline_library_music_24),@@ -75,22 +73,30 @@ fun HomeScreen(backStack: NavBackStack<Route>, viewModel: DatabaseViewModel) {             }, searchEnabled = true, bottomBar = {                 PlayingBottomBar(playbackManager, backStack)             }, fab = {-                FloatingActionButton({-                    coroutineScope.launch {-                        val allSongs = viewModel.getAll<Music>()-                        val toPlayIndex = Random.nextInt(allSongs.size)-                        playbackManager.playSong(allSongs, toPlayIndex)-                        if (!playbackManager.shuffleMode.value)-                            playbackManager.toggleShuffle()-                    }-                }) {-                    Icon(painterResource(R.drawable.ic_shuffle), null)-                }+                ShufflePlayFab(viewModel, playbackManager)             })         }     } } +@Composable+fun ShufflePlayFab(viewModel: DatabaseViewModel, playbackManager: PlaybackManager) {+    val coroutineScope = rememberCoroutineScope()++    FloatingActionButton({+        coroutineScope.launch {+            val allSongs = viewModel.getAll<Music>()+            val toPlayIndex = Random.nextInt(allSongs.size)+            playbackManager.playSong(allSongs, toPlayIndex)+            if (!playbackManager.shuffleMode.value)+                playbackManager.toggleShuffle()+        }+    }) {+        Icon(painterResource(R.drawable.ic_shuffle), null)+    }+}++ @Composable fun PlayingBottomBar(     playbackManager: PlaybackManager,
notes/src/main/java/com/vayunmathur/notes/ui/NotePage.kt
diff --git a/notes/src/main/java/com/vayunmathur/notes/ui/NotePage.kt b/notes/src/main/java/com/vayunmathur/notes/ui/NotePage.ktindex 7795dbf425..e097c9ffd5 100644--- a/notes/src/main/java/com/vayunmathur/notes/ui/NotePage.kt+++ b/notes/src/main/java/com/vayunmathur/notes/ui/NotePage.kt@@ -52,9 +52,8 @@ fun NotePage(backStack: NavBackStack<Route>, viewModel: DatabaseViewModel, noteI                 if(isEditing) IconVisible() else IconEdit()             }             IconButton(onClick = {-                viewModel.delete(note) {-                    backStack.pop()-                }+                viewModel.delete(note)+                backStack.pop()             }) {                 IconDelete()             }
openassistant/src/main/java/com/vayunmathur/openassistant/InferenceService.kt
diff --git a/openassistant/src/main/java/com/vayunmathur/openassistant/InferenceService.kt b/openassistant/src/main/java/com/vayunmathur/openassistant/InferenceService.ktindex e3207f94b4..6ef36b293c 100644--- a/openassistant/src/main/java/com/vayunmathur/openassistant/InferenceService.kt+++ b/openassistant/src/main/java/com/vayunmathur/openassistant/InferenceService.kt@@ -263,14 +263,14 @@ class InferenceService : Service() {      // Database interaction placeholders - implementation should be provided by your DB layer     private suspend fun fetchHistoryFromDb(id: Long): List<Message> = viewModel.getAll<Message>().filter { it.conversationId == id }-    private suspend fun upsertMessageToDb(msg: Message): Long = viewModel.getDaoInterface<Message>().dao.upsert(msg)+    private suspend fun upsertMessageToDb(msg: Message): Long = viewModel.upsert(msg)     private suspend fun updateMessageInDb(id: Long, text: String) {-        val newMsg = viewModel.getAll<Message>().find { it.id == id }!!.copy(text = text)+        val newMsg = viewModel.get<Message>(id).copy(text = text)         upsertMessageToDb(newMsg)     }     private suspend fun updateTitleInDb(id: Long, title: String) {-        val newMsg = viewModel.getAll<Conversation>().find { it.id == id }!!.copy(title = title)-        viewModel.getDaoInterface<Conversation>().dao.upsert(newMsg)+        val newMsg = viewModel.get<Conversation>(id).copy(title = title)+        viewModel.upsert(newMsg)     }      override fun onDestroy() {
openassistant/src/main/java/com/vayunmathur/openassistant/LiteRTChatUi.kt
diff --git a/openassistant/src/main/java/com/vayunmathur/openassistant/LiteRTChatUi.kt b/openassistant/src/main/java/com/vayunmathur/openassistant/LiteRTChatUi.ktindex 9e22530068..ee2a005f51 100644--- a/openassistant/src/main/java/com/vayunmathur/openassistant/LiteRTChatUi.kt+++ b/openassistant/src/main/java/com/vayunmathur/openassistant/LiteRTChatUi.kt@@ -350,10 +350,7 @@ fun LiteRTChatUi(backStack: NavBackStack<Route>, conversationId: Long, viewModel                                             var currentId = conversationId                                             if (currentId == 0L) {                                                 val newConv = Conversation(title = "New Conversation")-                                                currentId =-                                                    viewModel.getDaoInterface<Conversation>().dao.upsert(-                                                        newConv-                                                    )+                                                currentId = viewModel.upsert(newConv)                                                 backStack.reset(Route.ConversationPage(currentId))                                             } @@ -366,7 +363,7 @@ fun LiteRTChatUi(backStack: NavBackStack<Route>, conversationId: Long, viewModel                                                 hasAudio = recordedAudioFile != null,                                                 timestamp = Clock.System.now().toEpochMilliseconds()                                             )-                                            viewModel.getDaoInterface<Message>().dao.upsert(userMsg)+                                            viewModel.upsert(userMsg)                                              // 2. Start Service with the message payload                                             val intent =
passwords/src/main/java/com/vayunmathur/passwords/PasswordAutofillService.kt
diff --git a/passwords/src/main/java/com/vayunmathur/passwords/PasswordAutofillService.kt b/passwords/src/main/java/com/vayunmathur/passwords/PasswordAutofillService.ktindex 6b897c0911..a6e96d1ca4 100644--- a/passwords/src/main/java/com/vayunmathur/passwords/PasswordAutofillService.kt+++ b/passwords/src/main/java/com/vayunmathur/passwords/PasswordAutofillService.kt@@ -104,9 +104,9 @@ class PasswordAutofillService : AutofillService() {                 val existing = viewModel.getAll<Password>().firstOrNull { it.userId == username }                  if (existing != null) {-                    viewModel.upsert(existing.copy(password = password))+                    viewModel.upsertAsync(existing.copy(password = password))                 } else {-                    viewModel.upsert(+                    viewModel.upsertAsync(                         Password(                             name = "New Login",                             userId = username,
passwords/src/main/java/com/vayunmathur/passwords/ui/PasswordEditPage.kt
diff --git a/passwords/src/main/java/com/vayunmathur/passwords/ui/PasswordEditPage.kt b/passwords/src/main/java/com/vayunmathur/passwords/ui/PasswordEditPage.ktindex 3d5f122fca..d9f36a0f2e 100644--- a/passwords/src/main/java/com/vayunmathur/passwords/ui/PasswordEditPage.kt+++ b/passwords/src/main/java/com/vayunmathur/passwords/ui/PasswordEditPage.kt@@ -96,13 +96,12 @@ fun PasswordEditPage(backStack: NavBackStack<Route>, id: Long, viewModel: Databa                 )                  if (pass.isNew()) {-                    viewModel.upsert(newPass) { id ->+                    viewModel.upsertAsync(newPass) { id ->                         backStack.setLast(Route.PasswordPage(id))                     }                 } else {-                    viewModel.upsert(newPass) {-                        backStack.removeLastOrNull()-                    }+                    viewModel.upsertAsync(newPass)+                    backStack.removeLastOrNull()                 }             }) {                 IconSave()
passwords/src/main/java/com/vayunmathur/passwords/ui/SettingsPage.kt
diff --git a/passwords/src/main/java/com/vayunmathur/passwords/ui/SettingsPage.kt b/passwords/src/main/java/com/vayunmathur/passwords/ui/SettingsPage.ktindex b8511409bc..6fdbf4af7e 100644--- a/passwords/src/main/java/com/vayunmathur/passwords/ui/SettingsPage.kt+++ b/passwords/src/main/java/com/vayunmathur/passwords/ui/SettingsPage.kt@@ -142,7 +142,7 @@ private suspend fun importBitwardenCsvFromUri(contentResolver: ContentResolver,                 val websites = uriField.split(';', '\n', '\r').mapNotNull { it.trim().takeIf(String::isNotEmpty) }                  val pass = Password(name = name, userId = username, password = password, totpSecret = totp, websites = websites)-                viewModel.upsert(pass)+                viewModel.upsertAsync(pass)                 inserted++             } catch (_: Exception) {                 skipped++
youpipe/src/main/java/com/vayunmathur/youpipe/ui/ChannelPage.kt
diff --git a/youpipe/src/main/java/com/vayunmathur/youpipe/ui/ChannelPage.kt b/youpipe/src/main/java/com/vayunmathur/youpipe/ui/ChannelPage.ktindex cf14feba7f..19f6588ad0 100644--- a/youpipe/src/main/java/com/vayunmathur/youpipe/ui/ChannelPage.kt+++ b/youpipe/src/main/java/com/vayunmathur/youpipe/ui/ChannelPage.kt@@ -81,7 +81,7 @@ fun ChannelPage(backStack: NavBackStack<Route>, viewModel: DatabaseViewModel, ch                 val existingSubscription = subscriptions.firstOrNull { it.channelID == channelID }                 if(existingSubscription == null) {                     Button({-                        viewModel.upsert(Subscription(name = it.name, channelID = channelID, avatarURL = it.avatar))+                        viewModel.upsertAsync(Subscription(name = it.name, channelID = channelID, avatarURL = it.avatar))                     }, Modifier.fillMaxWidth().padding(horizontal = 8.dp)) {                         Text("Subscribe")                     }
youpipe/src/main/java/com/vayunmathur/youpipe/ui/VideoPlayer.kt
diff --git a/youpipe/src/main/java/com/vayunmathur/youpipe/ui/VideoPlayer.kt b/youpipe/src/main/java/com/vayunmathur/youpipe/ui/VideoPlayer.ktindex 952b29dc59..9d1f80ab61 100644--- a/youpipe/src/main/java/com/vayunmathur/youpipe/ui/VideoPlayer.kt+++ b/youpipe/src/main/java/com/vayunmathur/youpipe/ui/VideoPlayer.kt@@ -154,7 +154,7 @@ fun VideoPlayer(         while (true) {             if (!isDragging && player.isPlaying) {                 currentPosition = player.currentPosition.coerceAtLeast(0L)-                viewModel.upsert(HistoryVideo.fromVideoData(videoInfo.copy(duration = duration), currentPosition))+                viewModel.upsertAsync(HistoryVideo.fromVideoData(videoInfo.copy(duration = duration), currentPosition))             }             delay(300)         }
youpipe/src/main/java/com/vayunmathur/youpipe/ui/dialog/CreateSubscriptionCategory.kt
diff --git a/youpipe/src/main/java/com/vayunmathur/youpipe/ui/dialog/CreateSubscriptionCategory.kt b/youpipe/src/main/java/com/vayunmathur/youpipe/ui/dialog/CreateSubscriptionCategory.ktindex f581cf1f67..e9e7742dc1 100644--- a/youpipe/src/main/java/com/vayunmathur/youpipe/ui/dialog/CreateSubscriptionCategory.kt+++ b/youpipe/src/main/java/com/vayunmathur/youpipe/ui/dialog/CreateSubscriptionCategory.kt@@ -41,7 +41,7 @@ import kotlinx.coroutines.launch @OptIn(ExperimentalMaterial3Api::class) @Composable fun CreateSubscriptionCategory(backStack: NavBackStack<Route>, viewModel: DatabaseViewModel, id: String?) {-    val categoriesDao = viewModel.getDaoInterface<SubscriptionCategory>().dao as SubscriptionCategoryDao+    val categoriesDao = viewModel.getDao<SubscriptionCategory>() as SubscriptionCategoryDao     val subscriptions by viewModel.data<Subscription>().collectAsState()     val categories by viewModel.data<SubscriptionCategory>().collectAsState()     val categoryNames = categories.map { it.category }