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()
CodePudding user response:
Then try this:
fun addUser(user: User, callBack: (Long) -> Unit) {
viewModelScope.launch(Dispatchers.IO) {
userID = roomUserRepository.addUser(user)
callBack(userID)
}
}
// Create User
user.email = email
user.fullName = fullname
user.password = password
userVM.addUser(user) { id ->
cart.userID = id
cartVM.addCart(cart)
Log.d("user & cart", "adding users & cart")
}
CodePudding user response:
based on the docs, the return value of the below function is the rowId, not the userID.
@Insert(onConflict = IGNORE)
fun addUser(user: User): Long
If you want to get the userID, you should write a get function like below.
@Query("SELECT * FROM user_table)
fun getUsers(): Flow<List<User>>
Then, add an observer like below
val users = roomUserRepository.getUsers().asLiveData()
Also don't forget to add the necessary dependencies.
// ViewModel
implementation "androidx.lifecycle:lifecycle-viewmodel-ktx:$lifecycle_version"
// LiveData
implementation "androidx.lifecycle:lifecycle-livedata-ktx:$lifecycle_version"
// Coroutines
implementation "org.jetbrains.kotlinx:kotlinx-coroutines-android:$kotlin_version"