How I can wait until the value get updated then I use it

Issue

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()

Solution

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")
}

Answered By – Muhammed Talha Sa─člam

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published