Wait for a search add in the ViewModel's scope (#95)
This commit is contained in:
1 parent
46cd126bf1
commit
3cbeff7bdc
1 file changed
+16
-10
@@ -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)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Reference in new issue
Block a user