Home > Software design >  What is the best way of updating a state when navigating back to a screen in jetpack compose?
What is the best way of updating a state when navigating back to a screen in jetpack compose?

Time:04-14

I've got two screens: first is a list of todo's and second is a screen for adding a todo and I can navigate from one to another with navController. When I add a new todo item on the second screen, the data from database changes and I return to the screen with list of todo's but it does not contain the new one because function viewModel.getAllTodos() was not executed. Where and when should I execute it after adding a new todo to see updated list after returning to it?

CodePudding user response:

The best way would be to have those TODOs stored in a Room database, so that you can observe the changes.

DAO:

@Query("SELECT * FROM todos")
fun getAllTodos(): Flow<List<Todo>>

Then, in your TODO list screen, just use getAllTodos().collectAsState(emptyList()). In order to access this method from the DAO, I'd suggest using Hilt to inject a repository containing the abstract method into the ViewModel.

  • Related