Android Studio 如何等到值更新后再使用它

6ljaweal  于 2022-11-16  发布在  Android
关注(0)|答案(2)|浏览(114)

实体类别

@Entity(tableName = "user_table")
data class User(
    @PrimaryKey(autoGenerate = true)
    //....
) {

    constructor(
        userID: Int
    ) : this(
        userID,
        //...
    )
}

刀类

@Dao
interface UserDao {
    @Insert(onConflict = IGNORE)
    fun addUser(user: User): Long
    
    //.......
}

资料档案库类

class RoomUserRepository(context: Context) {
    //...
    suspend fun addUser(user: User): Long = userDao.addUser(user)
    //...
}

视图模式类

class UserViewModel(val context: Application) : AndroidViewModel(context) {
    //...

    var userID: Long = 0

    fun addUser(user: User) {
        viewModelScope.launch(Dispatchers.IO) {
            userID = roomUserRepository.addUser(user)
        }
    }

    //...
}

注册按钮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")
}

正如您所看到的,当用户单击SIGN UP时,我将在我的数据库中创建User & Cart,用户创建工作正常,但当我创建购物车时,我必须传递用户ID,我从userID变量中获取它,您可以在ViewMode Class中找到它,问题是值正在获取cart.userID = userVM.userID.toInt(),然后更新了它
我只想
调用userVM.addUser(user)后,我必须等到userID变量得到更新(查看ViewMode类),然后我得到更新后的值cart.userID = userVM.userID.toInt()

4jb9z9bj

4jb9z9bj1#

那就试试这个:

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

ha5z0ras2#

根据文档,下面的函数的返回值是rowId,而不是userID。

@Insert(onConflict = IGNORE)
fun addUser(user: User): Long

如果你想得到用户ID,你应该写一个get函数,如下所示。

@Query("SELECT * FROM user_table)
   fun getUsers(): Flow<List<User>>

然后,添加如下所示的观察者

val users = roomUserRepository.getUsers().asLiveData()

另外,不要忘记添加必要的依赖项。

// 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"

相关问题