How to avoid hoisting state to an app-level?

41 views Asked by At

I have an Android app in Jetpack Compose. I have a screen where the user can create a new player.

New Player screen

On this screen, the user can type in a Player name and select a color. Then, the user presses the checkmark in the top right corner and saves the player into the database. My problem here is that this screen is created using an app-wide Scaffold. The top app bar is a TopAppBar and thus the onClick function of the checkmark button doesn't have access to the player name and color from the screen, since the screen is a screen rendered using a NavHost.

When is the cleanest approach for this situation? I've come up with a possible solution.

The solution is to have a var player = remember { mutableStateOf(Player()) } on my App() composable and then hoist the onPlayerChange: (player: Player) -> Unit event handler up, but that seems very dirty to me.

I have asked ChatGPT, and it came up with a shared ViewModel solution, but that would mean that when I press the checkmark to save the player, I would have to acquire an instance of the ViewModel inside the onClick listener of the button, which doesn't sit right with me.

0

There are 0 answers