Entity class
@Entity(tableName = "user_table")
data class User(
@PrimaryKey(autoGenerate = true)
//....
) {
constructor(
userID: Int
) : this(
userID,
//...
)
}
Dao class
@Dao
interface UserDao {
@Insert(onConflict = IGNORE)
fun addUser(user: User): Long
//.......
}
Repository Class
class RoomUserRepository(context: Context) {
//...
suspend fun addUser(user: User): Long = userDao.addUser(user)
//...
}
ViewMode Class
class UserViewModel(val context: Application) : AndroidViewModel(context) {
//...
var userID: Long = 0
fun addUser(user: User) {
viewModelScope.launch(Dispatchers.IO) {
userID = roomUserRepository.addUser(user)
}
}
//...
}
SIGN UP Button onclick{}
clicked = !clicked
if (confirmpassword != password) {
message = "Incorrect password! please try again"
} else if (inputChack(fullname, email, password)) {
message = "Information is incomplete"
} else {
// Create User
user.email = email
user.fullName = fullname
user.password = password
userVM.addUser(user)
// Create Cart
cart.userID = userVM.userID.toInt()
cartVM.addCart(cart)
Log.d("user & cart", "adding users & cart")
}
As you can see when the user click on SIGN UP
I will Create User & Cart
in my database, user creation work fine but when I create cart I have to pass user ID and I am getting it from userID
variable you can find it in ViewMode Class
the problem is the value is getting cart.userID = userVM.userID.toInt()
then it been updated
Simply I want
After called userVM.addUser(user)
I have to wait until the userID
variable get updated (look at ViewMode Class) then I get the updated value cart.userID = userVM.userID.toInt()
2
Answers
based on the docs,
the return value of the below function is the rowId, not the userID.
If you want to get the userID, you should write a get function like below.
Then, add an observer like below
Also don’t forget to add the necessary dependencies.
Then try this: