I need to get the Auto generated ID of a record added to a ROOM database table.
Looking to answer my problem I found the following answer:text
But in my case is not a solution because in Compose I can't use the code:lifecycleScope.launch
//DAO@Insertsuspend fun addwarrantyget(warrantyEntity: WarrantyEntity): Long//Repositorysuspend fun addwarrantyget(warrantyEntity: WarrantyEntity):Long { return inventoryDB.warrantyDao().addwarrantyget(warrantyEntity) }//viewModelfun addwarrantyget(warranty: WarrantyEntity) = viewModelScope.launch { repository.addwarrantyget(warranty) }//Inside Compose FunlifecycleScope.launch { val id = viewModel.addwarrantyget(warranty) Log.i("INSERT_ID", "Inserted ID is: $id")}
As per suggestion and my understanding:
I added:
//viewModel
private val _newItemId = MutableStateFlow(-1L)val newItemId: StateFlow<Long> = _newItemIdfun addwarrantyget(warranty: WarrantyEntity) = viewModelScope.launch { val newId = repository.addwarrantyget(warranty) _newItemId.emit(newId!!)}
//Compose function extract
Button( onClick = { viewModel.addwarrantyget( WarrantyEntity( 0, null, insn, indescription, null, instartdateP.value, inenddateP.value, inprovider, instartdateM.value, inenddateM.value, inmanufacturer ) ) val newItemID by viewModel.newItemId.collectAsStateWithLifecycle() LaunchedEffect(newItemID) { if (newItemID == -1L) return@LaunchedEffect // Do what you need with the new id here warrantyId.value = viewModel.newItemId mToast("Warranty Added", mContext) } mToast("Warranty Added", mContext) }, colors = ButtonDefaults.buttonColors(Color.Blue) ) { Text(text = "Add Warranty") }
collectAsStateWithLifecycle: gives undefined reference error
warrantyId.value = viewModel.newItemId: gives Require Long Found StateFlow error
LaunchedEffect: gives @Composable invocations can only happen from the context...