ely*_*ya5 4 android android-room android-livedata
Flow我对使用withRoom进行数据库访问感到困惑。我希望能够观察表的变化,同时也可以直接访问它。但是,当使用返回 a 的查询时Flow,结果似乎总是这样null,尽管表不为空。直接返回 a 的查询List似乎有效。
有人可以解释其中的差异或告诉我我可能错过了文档的哪一部分吗?
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
db_button.setOnClickListener {
val user_dao = UserDatabase.getInstance(this).userDatabaseDao
lifecycleScope.launch {
user_dao.insertState(State(step=4))
val states = user_dao.getAllState().asLiveData().value
if (states == null || states.isEmpty()) {
println("null")
} else {
val s = states.first().step
println("step $s")
}
val direct = user_dao.getStatesDirect().first().step
println("direct step $direct")
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
@Entity(tableName = "state")
data class State(
@PrimaryKey(autoGenerate = true)
var id: Int = 0,
@ColumnInfo(name = "step")
var step: Int = 0
)
@Dao
interface UserDatabaseDao {
@Insert
suspend fun insertState(state: State)
@Query("SELECT * FROM state")
fun getAllState(): Flow<List<State>>
@Query("SELECT * FROM state")
suspend fun getStatesDirect(): List<State>
}
Run Code Online (Sandbox Code Playgroud)
输出:
I/System.out: null
I/System.out: direct step 1
Run Code Online (Sandbox Code Playgroud)
在 中Room,我们使用Flow或LiveData来观察查询结果的变化。因此,异步Room查询db,当您尝试立即检索值时,很可能会得到null.
因此,如果您想立即获取该值,则不应将其用作Flow房间查询函数的返回类型,就像您在getStatesDirect(): List<State>. 另一方面,如果你想观察数据变化,你应该使用上的收集终端函数来Flow接收其发射:
lifecycleScope.launch {
user_dao.insertState(State(step=4))
val direct = user_dao.getStatesDirect().first().step
println("direct step $direct")
}
lifecycleScope.launch {
user_dao.getAllState().collect { states ->
if (states == null || states.isEmpty()) {
println("null")
} else {
val s = states.first().step
println("step $s")
}
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1551 次 |
| 最近记录: |