Сегодня мой первый опыт работы с сопрограммами, поэтому я не совсем понимаю, как все работает. Я пробовал различные комбинации приостановки и отключения функций, запуска в GlobalScope, работы в области сопрограмм с поддержкой компоновки и т. д. Встроенный Gemini в Android Studio, как всегда, был скорее проблемой, чем помощником.
Ниже приведен мой код.
Кнопка:
Код: Выделить всё
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)
)
}
Код: Выделить всё
@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
Подробнее здесь: https://stackoverflow.com/questions/798 ... r-an-event
Мобильная версия