So I have the following Screen in my app –
fun TodoListPage(viewModel: TodoViewModel,
modifier: Modifier = Modifier,
navHost: NavHostController,
paddingValues: PaddingValues,
authViewModel: AuthViewModel ) {
val todoList by viewModel.todoList.observeAsState()
// Code to show todoList
}
In my view Model I have the following code –
class TodoViewModel: ViewModel() {
private var _todoList = MutableLiveData<SnapshotStateList<TodoItem>>()
var todoList : LiveData<SnapshotStateList<TodoItem>> = _todoList
init {
getAllToDo()
}
fun getAllToDo(){
_todoList.value = TodoManager.getAllToDo()
Log.d("TodoManager", "getAllToDo: ${todoList.value.toString()}")
}
}
And in my Manager getAllToDo()
fun getAllToDo(): SnapshotStateList<TodoItem> {
val user = Firebase.auth.currentUser
val tempList = SnapshotStateList<TodoItem>()
user?.let {
Firebase.firestore.collection(it.uid).get()
.addOnSuccessListener { documents ->
for (document in documents) {
val todoItem = document.toObject(TodoItem::class.java)
tempList.add(todoItem)
}
Log.d("TempList", "$tempList")
todoList = tempList
Log.d("TodoList", "$todoList")
}
}
return todoList
}
When I run my code, I get the following Log statements,
2024-06-10 19:44:50.675 3730-3730 TodoManager
2024-06-10 19:44:52.609 3730-3730 TempList
2024-06-10 19:44:52.609 3730-3730 TodoList
I wanted to understand how I should fix this, and why my UI is not getting updated after my todoList is updated.
I understand that the Manager runs first, and by that point the list is empty so my Screen is not populated, but once the query to get the data from firestore finishes, shouldn’t the state change and the UI recompose?
UMANG SHARMA is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.