Heute habe ich zum ersten Mal Erfahrungen mit Coroutinen gemacht, daher verstehe ich nicht wirklich, wie die Dinge funktionieren. Ich habe verschiedene Kombinationen ausprobiert, um Funktionen anzuhalten und nicht, in GlobalScope auszuführen, in Composable-fähigem Coroutine-Bereich usw. auszuführen. Das integrierte Gemini in Android Studio war wie immer eher ein Problem als ein Helfer.
Unten ist mein Code.
Die Schaltfläche:
Code: Select all
val localctx = LocalContext.current
val coroutineScope = rememberCoroutineScope()
Button(
onClick = {
var newEntryUuid = Uuid.random()
val newEntryUuidClone = newEntryUuid
coroutineScope.launch(Dispatchers.IO) {
if (newEntryViewModel.selectedEntryType == EntryTypes.Card)
newEntryUuid = newEntryViewModel.pushNewEntry(card = newEntryViewModel.createCard(), context = localctx)
if (newEntryViewModel.selectedEntryType == EntryTypes.Account)
newEntryUuid = newEntryViewModel.pushNewEntry(account = newEntryViewModel.createAccount(), context = localctx)
newEntryViewModel.entryCreated.value = newEntryUuid != newEntryUuidClone
}
},
enabled = newEntryViewModel.allRequiredFieldsAreFilled,
colors = ButtonColors(
containerColor = MaterialTheme.colorScheme.primaryContainer,
contentColor = MaterialTheme.colorScheme.onPrimaryContainer,
disabledContainerColor = Color.LightGray,
disabledContentColor = Color.DarkGray
),
modifier = Modifier
.fillMaxWidth()
.padding(top = 16.dp)
) {
Text(stringResource(R.string.continue_button))
}
Spacer(
modifier = Modifier.height(80.dp)
)
}
Code: Select all
@OptIn(DelicateCoroutinesApi::class)
suspend fun pushNewEntry(account: Account, context: Context): Uuid {
return withContext(Dispatchers.IO) {
val database = DatabaseProvider.getDatabase(context)
val newAccUuid = AccountManager.createAccount(
database = database,
account = account,
encryptionKey = VaultHandler().getEncryptionKey(context)
)
if (selectedFolderUuid != null) {
FolderManager.performEntryFolderOper(
database = database,
operation = FolderManager.EntryFolderOperations.Add,
entryUuid = newAccUuid,
targetFolderUuid = selectedFolderUuid as Uuid
)
}
newAccUuid
}
}
// the very same thing but with a card type
Mobile version