Android次更新房间后,更新其他livedata
After Android update the room, other livedata is update
我的数据库有两个数据,我有两个livedata来观察这两个数据,当我更新一条数据时,livedata1变了,但是问题来了,livedata2也变了。这是我的代码,这有什么问题。
val userDB = UserDB.getInstance(this)
var userDao = userDB?.getUserDao()
val live0: LiveData<List<UserBean>>? = userDao?.getUser(0)
val live1: LiveData<List<UserBean>>? = userDao?.getUser(1)
val userBean1 = UserBean("jack", 10, 1)
val userBean2 = UserBean("david", 20, 0)
CoroutineScope(Dispatchers.IO).launch {
(0..5).forEach {
delay(1000)
userDao?.updateUserAge(it, "jack")
}
}
live0?.observe(this, {
it.forEach { index ->
Log.e("live0 ------->",
"id = ${index.id} ,name = ${index.userName} ,age = ${index.age} ,gender = ${index.gender}")
}
})
live1?.observe(this, {
it.forEach { index ->
Log.e("live1 ------->",
"id = ${index.id} ,name = ${index.userName} ,age = ${index.age} ,gender = ${index.gender}")
}
})
@Dao
接口 UserDao {
@Insert
fun insertUsers(vararg users: UserBean)
@Query("UPDATE UserBean SET age =:age WHERE name =:name")
suspend fun updateUserAge(age: Int, name: String)
@Query("SELECT * FROM UserBean where gender =:gender ORDER BY ID DESC")
fun getUser(gender: Int): LiveData<List<UserBean>>
}
这是我的 logcat
enter image description here
当您在 table 中进行任何更改时,实时数据会向您发送更新,因此它工作正常,您必须围绕此构建逻辑。
我的数据库有两个数据,我有两个livedata来观察这两个数据,当我更新一条数据时,livedata1变了,但是问题来了,livedata2也变了。这是我的代码,这有什么问题。
val userDB = UserDB.getInstance(this)
var userDao = userDB?.getUserDao()
val live0: LiveData<List<UserBean>>? = userDao?.getUser(0)
val live1: LiveData<List<UserBean>>? = userDao?.getUser(1)
val userBean1 = UserBean("jack", 10, 1)
val userBean2 = UserBean("david", 20, 0)
CoroutineScope(Dispatchers.IO).launch {
(0..5).forEach {
delay(1000)
userDao?.updateUserAge(it, "jack")
}
}
live0?.observe(this, {
it.forEach { index ->
Log.e("live0 ------->",
"id = ${index.id} ,name = ${index.userName} ,age = ${index.age} ,gender = ${index.gender}")
}
})
live1?.observe(this, {
it.forEach { index ->
Log.e("live1 ------->",
"id = ${index.id} ,name = ${index.userName} ,age = ${index.age} ,gender = ${index.gender}")
}
})
@Dao
接口 UserDao {
@Insert
fun insertUsers(vararg users: UserBean)
@Query("UPDATE UserBean SET age =:age WHERE name =:name")
suspend fun updateUserAge(age: Int, name: String)
@Query("SELECT * FROM UserBean where gender =:gender ORDER BY ID DESC")
fun getUser(gender: Int): LiveData<List<UserBean>>
}
这是我的 logcat enter image description here
当您在 table 中进行任何更改时,实时数据会向您发送更新,因此它工作正常,您必须围绕此构建逻辑。