notes: refactor VM to use NoteDao directly
- Commit
fe72bdaa5c9d5192d89a2df59b94a8f73a33aca3- Author
- Vayun Mathur <[email protected]>
- When
- 2026-05-29 18:20 UTC (6 months ago)
- Parents
75635fc
Diff
notes/src/main/java/com/vayunmathur/notes/MainActivity.kt
diff --git a/notes/src/main/java/com/vayunmathur/notes/MainActivity.kt b/notes/src/main/java/com/vayunmathur/notes/MainActivity.ktindex f1ab04bb41..5ee73b9484 100644--- a/notes/src/main/java/com/vayunmathur/notes/MainActivity.kt+++ b/notes/src/main/java/com/vayunmathur/notes/MainActivity.kt@@ -11,7 +11,6 @@ import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import com.vayunmathur.library.ui.DynamicTheme-import com.vayunmathur.library.util.DatabaseViewModel import com.vayunmathur.library.util.IntentHelper import com.vayunmathur.library.util.ListDetailPage import com.vayunmathur.library.util.ListPage@@ -20,7 +19,7 @@ import com.vayunmathur.library.util.NavKey import com.vayunmathur.library.util.buildDatabase import com.vayunmathur.library.util.onFileDrop import com.vayunmathur.library.util.rememberNavBackStack-import com.vayunmathur.notes.data.Note+import com.vayunmathur.notes.data.NoteDao import com.vayunmathur.notes.data.NoteDatabase import com.vayunmathur.notes.ui.NotePage import com.vayunmathur.notes.ui.NotesListPage@@ -29,16 +28,16 @@ import com.vayunmathur.notes.util.NotesViewModelFactory import kotlinx.serialization.Serializable class MainActivity : ComponentActivity() {- private lateinit var viewModel: DatabaseViewModel+ private lateinit var noteDao: NoteDao private val notesViewModel: NotesViewModel by viewModels {- NotesViewModelFactory(application, viewModel)+ NotesViewModelFactory(application, noteDao) } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) enableEdgeToEdge() val db = buildDatabase<NoteDatabase>(dbName = "notes-db")- viewModel = DatabaseViewModel(db, Note::class to db.noteDao())+ noteDao = db.noteDao() handleIntent(intent) @@ -47,7 +46,7 @@ class MainActivity : ComponentActivity() { Box(Modifier.fillMaxSize().onFileDrop { uris -> notesViewModel.importFiles(uris) }) {- Navigation(viewModel, notesViewModel)+ Navigation(notesViewModel) } } }@@ -77,14 +76,14 @@ sealed interface Route: NavKey { } @Composable-fun Navigation(viewModel: DatabaseViewModel, notesViewModel: NotesViewModel) {+fun Navigation(notesViewModel: NotesViewModel) { val backStack = rememberNavBackStack<Route>(Route.NotesList) MainNavigation(backStack) { entry<Route.NotesList>(metadata = ListPage()) {- NotesListPage(backStack, viewModel)+ NotesListPage(backStack, notesViewModel) } entry<Route.Note>(metadata = ListDetailPage()) {- NotePage(backStack, viewModel, notesViewModel, it.id)+ NotePage(backStack, notesViewModel, it.id) } } }
notes/src/main/java/com/vayunmathur/notes/data/NoteDatabase.kt
diff --git a/notes/src/main/java/com/vayunmathur/notes/data/NoteDatabase.kt b/notes/src/main/java/com/vayunmathur/notes/data/NoteDatabase.ktindex 3cecefbd87..33a9e1c1d2 100644--- a/notes/src/main/java/com/vayunmathur/notes/data/NoteDatabase.kt+++ b/notes/src/main/java/com/vayunmathur/notes/data/NoteDatabase.kt@@ -2,11 +2,30 @@ package com.vayunmathur.notes.data import androidx.room.Dao import androidx.room.Database+import androidx.room.Delete+import androidx.room.Query import androidx.room.RoomDatabase+import androidx.room.Upsert import com.vayunmathur.library.util.TrueDao+import kotlinx.coroutines.flow.Flow @Dao-interface NoteDao: TrueDao<Note>+interface NoteDao : TrueDao<Note> {+ @Query("SELECT * FROM Note")+ fun getAllFlow(): Flow<List<Note>>++ @Query("SELECT * FROM Note WHERE id = :id")+ fun getByIdFlow(id: Long): Flow<Note?>++ @Upsert+ override suspend fun upsert(value: Note): Long++ @Delete+ override suspend fun delete(value: Note): Int++ @Upsert+ override suspend fun upsertAll(t: List<Note>)+} @Database(entities = [Note::class], version = 1) abstract class NoteDatabase : RoomDatabase() {
notes/src/main/java/com/vayunmathur/notes/intents/GetIntent.kt
diff --git a/notes/src/main/java/com/vayunmathur/notes/intents/GetIntent.kt b/notes/src/main/java/com/vayunmathur/notes/intents/GetIntent.ktindex e297361b74..f68015a999 100644--- a/notes/src/main/java/com/vayunmathur/notes/intents/GetIntent.kt+++ b/notes/src/main/java/com/vayunmathur/notes/intents/GetIntent.kt@@ -2,8 +2,8 @@ package com.vayunmathur.notes.intents import com.vayunmathur.library.intents.notes.NoteData import com.vayunmathur.library.util.AssistantIntent-import com.vayunmathur.library.util.DatabaseViewModel import com.vayunmathur.library.util.buildDatabase+import com.vayunmathur.library.util.getAll import com.vayunmathur.notes.data.Note import com.vayunmathur.notes.data.NoteDatabase import kotlinx.serialization.InternalSerializationApi@@ -14,7 +14,6 @@ class GetIntent: AssistantIntent<Unit, List<NoteData>>(serializer<Unit>(), seria override suspend fun performCalculation(input: Unit): List<NoteData> { val db = buildDatabase<NoteDatabase>()- val viewModel = DatabaseViewModel(db, Note::class to db.noteDao())- return viewModel.getAll<Note>().map { NoteData(it.title, it.content) }+ return db.noteDao().getAll<Note>().map { NoteData(it.title, it.content) } }-}\ No newline at end of file+}
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 ce83591eae..bba04dc5b3 100644--- a/notes/src/main/java/com/vayunmathur/notes/ui/NotePage.kt+++ b/notes/src/main/java/com/vayunmathur/notes/ui/NotePage.kt@@ -51,7 +51,6 @@ import com.vayunmathur.library.ui.IconNavigation import com.vayunmathur.library.ui.IconSearch import com.vayunmathur.library.ui.IconShare import com.vayunmathur.library.ui.IconVisible-import com.vayunmathur.library.util.DatabaseViewModel import com.vayunmathur.library.util.NavBackStack import com.vayunmathur.library.R as LibraryR import com.vayunmathur.notes.Route@@ -62,11 +61,10 @@ import com.vayunmathur.notes.util.NotesViewModel @Composable fun NotePage( backStack: NavBackStack<Route>,- viewModel: DatabaseViewModel, notesViewModel: NotesViewModel, noteID: Long, ) {- var note by viewModel.getEditable<Note>(noteID) { Note(0, "", "") }+ var note by notesViewModel.editableNote(noteID) { Note(0, "", "") } if (noteID != 0L && note.id == 0L) return @@ -163,7 +161,7 @@ fun NotePage( IconShare() } IconButton(onClick = {- viewModel.delete(note)+ notesViewModel.delete(note) backStack.pop() }) { IconDelete()
notes/src/main/java/com/vayunmathur/notes/ui/NotesListPage.kt
diff --git a/notes/src/main/java/com/vayunmathur/notes/ui/NotesListPage.kt b/notes/src/main/java/com/vayunmathur/notes/ui/NotesListPage.ktindex d3fd252782..3010cf6f97 100644--- a/notes/src/main/java/com/vayunmathur/notes/ui/NotesListPage.kt+++ b/notes/src/main/java/com/vayunmathur/notes/ui/NotesListPage.kt@@ -3,24 +3,28 @@ package com.vayunmathur.notes.ui import androidx.compose.material3.IconButton import androidx.compose.material3.Text import androidx.compose.runtime.Composable+import androidx.compose.runtime.collectAsState+import androidx.compose.runtime.getValue+import androidx.compose.runtime.remember import androidx.compose.ui.platform.LocalContext-import com.vayunmathur.library.ui.IconDelete import com.vayunmathur.library.ui.BackupButtons-import com.vayunmathur.library.util.DatabaseHelper-import androidx.compose.runtime.remember+import com.vayunmathur.library.ui.IconDelete import com.vayunmathur.library.ui.ListPageR-import com.vayunmathur.library.util.DatabaseViewModel+import com.vayunmathur.library.util.DatabaseHelper import com.vayunmathur.library.util.NavBackStack import com.vayunmathur.notes.Route import com.vayunmathur.notes.data.Note+import com.vayunmathur.notes.util.NotesViewModel @Composable-fun NotesListPage(backStack: NavBackStack<Route>, viewModel: DatabaseViewModel) {+fun NotesListPage(backStack: NavBackStack<Route>, viewModel: NotesViewModel) { val context = LocalContext.current+ val notes by viewModel.notes.collectAsState() ListPageR<Note, Route, Route.Note>( backStack = backStack,- viewModel = viewModel,+ data = notes,+ onReorder = viewModel::upsertAll, title = "Notes", headlineContent = { Text(it.title)
notes/src/main/java/com/vayunmathur/notes/util/NotesViewModel.kt
diff --git a/notes/src/main/java/com/vayunmathur/notes/util/NotesViewModel.kt b/notes/src/main/java/com/vayunmathur/notes/util/NotesViewModel.ktindex f625609341..1e9f6a2038 100644--- a/notes/src/main/java/com/vayunmathur/notes/util/NotesViewModel.kt+++ b/notes/src/main/java/com/vayunmathur/notes/util/NotesViewModel.kt@@ -3,20 +3,32 @@ package com.vayunmathur.notes.util import android.app.Application import android.net.Uri import android.util.Log+import androidx.compose.runtime.Composable+import androidx.compose.runtime.LaunchedEffect+import androidx.compose.runtime.MutableState+import androidx.compose.runtime.collectAsState+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableLongStateOf+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.remember+import androidx.compose.runtime.setValue import androidx.compose.ui.text.AnnotatedString import androidx.core.content.FileProvider import androidx.lifecycle.AndroidViewModel import androidx.lifecycle.ViewModel import androidx.lifecycle.ViewModelProvider import androidx.lifecycle.viewModelScope-import com.vayunmathur.library.util.DatabaseViewModel import com.vayunmathur.library.util.IntentHelper import com.vayunmathur.library.util.parseMarkdown import com.vayunmathur.notes.data.Note+import com.vayunmathur.notes.data.NoteDao import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.flow.MutableSharedFlow import kotlinx.coroutines.flow.SharedFlow+import kotlinx.coroutines.flow.SharingStarted+import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.asSharedFlow+import kotlinx.coroutines.flow.stateIn import kotlinx.coroutines.launch import kotlinx.coroutines.withContext import java.io.File@@ -25,22 +37,76 @@ import java.io.File * ViewModel for the Notes app. * * Owns:+ * - the notes [StateFlow] (collected by screens)+ * - DB write helpers (upsert / delete / upsertAll) that dispatch on IO+ * - per-note editable state for the editor screen * - file import / drop handling (content-resolver + DB upsert) * - share-URI generation (cache file write + FileProvider URI) * - parsed-markdown cache (process-wide, keyed by content + search context)- *- * The shared [DatabaseViewModel] is injected so this VM can persist imported notes- * without leaking Compose state. Composables continue to use [DatabaseViewModel.getEditable]- * for per-note editing. */ class NotesViewModel( application: Application,- private val databaseViewModel: DatabaseViewModel,+ private val noteDao: NoteDao, ) : AndroidViewModel(application) { - private val _shareUris = MutableSharedFlow<Uri>(extraBufferCapacity = 1)- /** Emits a URI for a share intent each time [requestShare] completes. */- val shareUris: SharedFlow<Uri> = _shareUris.asSharedFlow()+ val notes: StateFlow<List<Note>> = noteDao.getAllFlow()+ .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), emptyList())++ fun upsert(note: Note) {+ viewModelScope.launch(Dispatchers.IO) { noteDao.upsert(note) }+ }++ fun delete(note: Note) {+ viewModelScope.launch(Dispatchers.IO) { noteDao.delete(note) }+ }++ fun upsertAll(notes: List<Note>) {+ viewModelScope.launch(Dispatchers.IO) { noteDao.upsertAll(notes) }+ }++ /**+ * Returns a [MutableState] backed by the DB row with the given id.+ *+ * On set, the new value is optimistically published locally and pushed to+ * the database off-thread. If [initialId] was 0L (a new row), the id is+ * updated after the first upsert returns so subsequent edits target the+ * same row.+ */+ @Composable+ fun editableNote(initialId: Long, default: () -> Note): MutableState<Note> {+ var currentId by remember { mutableLongStateOf(initialId) }++ val noteFlow = remember(currentId) { noteDao.getByIdFlow(currentId) }+ val dbNote by noteFlow.collectAsState(initial = null)++ val localState = remember { mutableStateOf<Note?>(null) }++ LaunchedEffect(dbNote, currentId) {+ val item = dbNote+ if (item != null) {+ localState.value = item+ }+ }++ return remember {+ object : MutableState<Note> {+ override var value: Note+ get() = localState.value ?: default()+ set(newValue) {+ localState.value = newValue+ viewModelScope.launch(Dispatchers.IO) {+ val newId = noteDao.upsert(newValue)+ if (currentId == 0L) {+ currentId = newId+ }+ }+ }++ override fun component1(): Note = value+ override fun component2(): (Note) -> Unit = { value = it }+ }+ }+ } private data class ParsedKey( val content: String,@@ -95,10 +161,13 @@ class NotesViewModel( return count } + private val _shareUris = MutableSharedFlow<Uri>(extraBufferCapacity = 1)+ /** Emits a URI for a share intent each time [requestShare] completes. */+ val shareUris: SharedFlow<Uri> = _shareUris.asSharedFlow()+ /**- * Reads each [uri] off the main thread and upserts it as a new [Note] via- * the shared [DatabaseViewModel]. Errors are logged per-file and do not- * abort the batch.+ * Reads each [uris] entry off the main thread and upserts it as a new [Note]+ * via [noteDao]. Errors are logged per-file and do not abort the batch. */ fun importFiles(uris: List<Uri>) { if (uris.isEmpty()) return@@ -110,7 +179,7 @@ class NotesViewModel( ?.bufferedReader()?.use { it.readText() } if (content != null) { val name = IntentHelper.getFileName(ctx, uri) ?: "Imported Note"- databaseViewModel.upsertAsync(Note(0, name, content))+ noteDao.upsert(Note(0, name, content)) } } catch (e: Exception) { Log.e(TAG, "Error importing file: $uri", e)@@ -147,16 +216,16 @@ class NotesViewModel( } } -/** Factory for constructing [NotesViewModel] with the shared [DatabaseViewModel]. */+/** Factory for constructing [NotesViewModel] with the [NoteDao]. */ class NotesViewModelFactory( private val application: Application,- private val databaseViewModel: DatabaseViewModel,+ private val noteDao: NoteDao, ) : ViewModelProvider.Factory { @Suppress("UNCHECKED_CAST") override fun <T : ViewModel> create(modelClass: Class<T>): T { require(modelClass.isAssignableFrom(NotesViewModel::class.java)) { "Unexpected ViewModel class: $modelClass" }- return NotesViewModel(application, databaseViewModel) as T+ return NotesViewModel(application, noteDao) as T } }