soyxan
soyxan

Reputation: 91

Jetpack Compose share Viewmodel between Activity and Composables

I have followed this tutorial to get the basic regarding ViewModel and Jetpack Compose: https://developer.android.com/codelabs/basic-android-kotlin-compose-viewmodel-and-state#0

In the above tutorial, in section 6 is shown the next Composable function which seems to initialize the ViewModel locally:

@Composable
fun GameScreen(
   gameViewModel: GameViewModel = viewModel()
) {
   // ...
}

Above approach is ok for the tutorial example as all the app logic resides in the ViewModel. The thing is that my app also needs to access the ViewModel (call some methods) from my MainActivity as my app needs to create and bind a custom process in the background from the MainActivity scope and the ViewModel needs to be updated based on the service status (started, stopped, events...) in order to consequently have the UI updated.

Is it right to create and bind the service form the MainActivity? Is it right to share the ViewModel between the MainActivity and the Composable functions? Which is the right way to do it? Initialize the ViewModel in the MainActivity and then pass it to all the Composable function?

Thanks!

Upvotes: 0

Views: 1373

Answers (1)

Hezy Ziv
Hezy Ziv

Reputation: 5558

Its common to share view models and the right way to manage shared state

class MainActivity : AppCompatActivity() {
    private val gameViewModel: GameViewModel by viewModels()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            MyApp(gameViewModel)
        }
    }
}

Upvotes: 1

Related Questions