I have created a register screen and am using the ROOM database to store the users. I am successfully adding them to the database. I am trying to run some validation on the entries as I do not want users to have the same username or email. Here is my code for adding them to the database and how I am validating it.
this is the function that sends the firstName, lastName, userName, password, address, city, postalCode, email, phone to the database.
the mCustomerViewModel.addCustomer(customer)
, returns a Boolean:
if it's true User Added
if its false, duplicate user
val customer = Customer(0, firstName, lastName, userName, password,address,city,postalCode,email,phone) val flag = mCustomerViewModel.addCustomer(customer) println("FLAG ---> " flag) if(flag.equals(true)){ Toast.makeText(applicationContext, "Success", Toast.LENGTH_SHORT).show() }else{ Toast.makeText(applicationContext, "Failed", Toast.LENGTH_SHORT).show() }
here is the CustomerViewModel
class:
fun addCustomer(customer: Customer){
viewModelScope.launch(Dispatchers.IO){
repository.addCustomer(customer) // call to CustomerRepository
}
and then from CustomerViewModel
class, we call CustomerRepository
fun addCustomer(customer: Customer): Boolean {
try {
customerDao.addCustomers(customer)
return true
}catch (ex: Exception){
return false
}
}
As you can see, in my function where the customer is being added, I have a print statement println("FLAG ---> " flag)
to check and see what the function was returning. I got this in the console:
When I run the app, the if statement doesn't run, only the else block does, because "flag" actually does not equal "true".
How can i fix this?
CodePudding user response:
Your addCustomer
function launches a coroutine and doesn't return anything (except the implicit Unit). Notice you did not define any return type. It is not possible for a non-suspend function to return the result of a launched coroutine because it returns before the coroutine necessarily has been run yet. You should either turn it into a suspend function that directly calls repository.addCustomer(customer)
without launching another coroutine, or you can give it a callback parameter to call at the end of the launched coroutine.
Third option is to change viewModelScope.launch
to return viewModelScope.async
and make the function return type Deferred<Boolean>
. Then when you need the result, you can call await()
on the Deferred in a coroutine.