From 3cbeff7bdc37c8de147be92cdd77684a5251d5a3 Mon Sep 17 00:00:00 2001 From: Jean-Luc Makiola Date: Fri, 20 Nov 2026 12:28:37 +0100 Subject: [PATCH] Wait for a search add in the ViewModel's scope (#95) --- .../agendula/ui/tasklist/TaskListViewModel.kt | 26 ++++++++++++------- 1 file changed, 16 insertions(+), 10 deletions(-) diff --git a/app/src/main/java/de/jeanlucmakiola/agendula/ui/tasklist/TaskListViewModel.kt b/app/src/main/java/de/jeanlucmakiola/agendula/ui/tasklist/TaskListViewModel.kt index b9aa548..5ecbe8b 100644 --- a/app/src/main/java/de/jeanlucmakiola/agendula/ui/tasklist/TaskListViewModel.kt +++ b/app/src/main/java/de/jeanlucmakiola/agendula/ui/tasklist/TaskListViewModel.kt @@ -54,6 +54,7 @@ import kotlinx.coroutines.flow.map import kotlinx.coroutines.flow.onStart import kotlinx.coroutines.flow.stateIn import kotlinx.coroutines.flow.update +import kotlinx.coroutines.async import kotlinx.coroutines.launch import kotlinx.coroutines.withContext import kotlinx.coroutines.withTimeoutOrNull @@ -495,23 +496,28 @@ class TaskListViewModel @Inject constructor( } /** - * Runs in the application scope so leaving the screen right after cannot - * cancel the write. The title stays pending until the new task shows up. + * The write runs in the application scope so leaving the screen right after + * cannot cancel it; the wait for the new task to show, which keeps the title + * pending, in this ViewModel's, so it ends with the screen. */ private fun add(title: String, listId: Long) { if (listId <= 0L) return val pending = pendingAdds.start(title) - appScope.launch { - val id = runCatching { repository.createTask(settingsPrefs.settings.first().quickTask(title, listId)) }.getOrNull() - withContext(Dispatchers.Main) { + val write = appScope.async { + runCatching { repository.createTask(settingsPrefs.settings.first().quickTask(title, listId)) }.getOrNull() + } + viewModelScope.launch { + try { + val id = write.await() showSearchReceipt(if (id != null) SearchReceipt.Added(title) else SearchReceipt.Failed()) - } - if (id != null) { - withTimeoutOrNull(PENDING_ADD_TIMEOUT_MS) { - state.first { st -> (st as? TaskListUiState.Content)?.searchable.orEmpty().any { it.taskId == id } } + if (id != null) { + withTimeoutOrNull(PENDING_ADD_TIMEOUT_MS) { + state.first { st -> (st as? TaskListUiState.Content)?.searchable.orEmpty().any { it.taskId == id } } + } } + } finally { + pendingAdds.finish(pending) } - pendingAdds.finish(pending) } }