我有一个访问数据库(Firebase)并计算文档数量的ViewModel.数据库的 struct 是:集合"Posts"-->;文档-->;集合"Like"-->;文档. 因此,我访问集合"post",然后对于包含我的用户名的每个文档,我访问集合"like"并获取快照大小,以计算有多少个赞.问题是,当创建一个新的Like文档时,在应用程序重新启动之前,ViewModel不会获得更新.
The way I am using the ViewModel:个 我有一个导航图,在那里我创建了一个ViewModel实例,然后我调用检索数据的函数,然后在需要数据的另一个屏幕中将该实例作为参数传递.在另一个屏幕中,我访问存储数据的变量.将数据存储在StateFlow中的变量(因为我在这里传递的是计数器值,而不是文档)
Code (ViewModel):个
class PointsViewModel : ViewModel() {
private val firebase = Firebase.firestore
private var _points = MutableStateFlow(0)
val points: StateFlow<Int> = _points
fun calculate(username: String){
firebase.collection("Posts")
.whereEqualTo("PostUser",username)
.get()
.addOnSuccessListener { posts ->
for(post in posts){
post.reference.collection("Likes").get().addOnSuccessListener { likes ->
_points.value += likes.size()
}
}
}
}
}
Code (Where I create instance in NavGraph):个
val pointsViewModel: PointsViewModel = viewModel()
//sharedViewModel contains the username
sharedViewModel.user?.username?.let { pointsViewModel.calculate(it) }
Code (Where I need the data):个
fun AwardsScreen(sharedViewModel: SharedViewModel,pointsViewModel: PointsViewModel){
val points by pointsViewModel.points.collectAsState()
Column(modifier = Modifier
.fillMaxWidth()
.padding(15.dp, 15.dp)) {
Row(modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.Center) {
Text(text = points.toString())
}
}
我试着在屏幕内进行所有这些操作,我需要数据.因此,我try 访问数据库并从那里检索所有数据,添加了一个快照侦听器来获取更新,但它不起作用