I'm working on a simple SoundBoard app to get familiar with Jetpack Compose and Navigation. I'm fairly new to both technologies and am struggling with this:
Main view in the app is a grid-like view of all sounds that are stored in an SQLite database. Users can edit a sound to change its name in a dialog. When the edit dialog is closed, I want to refresh the grid, but I haven't found a way how this is implemented ideally.
So far, I have these destinations:
object Destinations {
@Serializable
object SoundGrid
@Serializable
class SoundEdit(val soundId: Int)
}
And use them like this:
@Composable
fun SoundBoardApp(navController: NavHostController = rememberNavController()) {
NavHost(navController = navController, startDestination = SoundGrid) {
composable<SoundGrid> {
SoundGrid(
onNavigateToSoundEdit = {
navController.navigate(SoundEdit(it.id))
})
}
dialog<SoundEdit> {
SoundEditDialog(onClose = {
navController.navigateUp()
})
}
}
}
@Composable
fun SoundGrid(
onNavigateToSoundEdit: (Sound) -> Unit,
modifier: Modifier = Modifier,
viewModel: SoundGridViewModel = koinViewModel(),
) { .. }
@Composable
fun SoundEditDialog(
onClose: () -> Unit,
viewModel: SoundEditViewModel = koinViewModel()
) { .. }
How can I instruct the ViewModel of the SoundGrid composable to update the data when the dialog got closed? What is the ideal way of implementing this functionality?
Flowfrom your database so that any data changed will refresh the UI automatically. You can read more here: developer.android.com/training/data-storage/room/… This is a really nice-looking app by the way ;)Flowprovided by room works. What would be the solution if my data is provided by a REST API instead? Can't use a Flow in that case, if I'm not wrong?ViewModel.NavBackStackEntryis aViewModelStoreOwner, so using anyNavBackStackEntryyou can get an ViewModel for different scoped to it. I don't know how it implemented with koin but with no injectionviewModel(entry)or with dagger hilt you simply passhitViewModel(entry)to get same ViewModel for different destinations withval entry = navController.getBackStackEntry(SoundGrid)suspendfunctions that you can call from theviewModelScopein your ViewModel, then from the Composable call the ViewModel function. Or you could also look intocallbackFlow, though I haven't used that myself yet.