But while using fragments we can have different viewmodels for different fragments/screens.
In Compose, you use composable functions to display your screens - no need to use fragments anymore.
Can we achieve same with composable functions..like single activity, different composable functions for different screen and different viewmodel for different composable functions?
You can use different ViewModels for different composable functions if you need them. This is how you can do that:
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
DifferentViewModels()
}
}
}
@Composable
fun DifferentViewModels() {
Column {
FirstComposable()
SecondComposable()
}
}
@Composable
fun FirstComposable(firstViewModel: FirstViewModel = viewModel()) {
Text(firstViewModel.value)
}
@Composable
fun SecondComposable(secondViewModel: SecondViewModel = viewModel()) {
Text(secondViewModel.value)
}
class FirstViewModel() : ViewModel() {
val value = "Value from the first View Model"
}
class SecondViewModel() : ViewModel() {
val value = "Value from the second View Model"
}
Make sure to add the ViewModel dependency on your build.gradle(Module) file:
// Compose ViewModel
implementation "androidx.lifecycle:lifecycle-viewmodel-compose:1.0.0-alpha07"
if yes,is this ideal approach?
It depends on your project requirements. If you have different big screens where you need to store many different values and you don't need to share them with different screens, you can use different ViewModels for them.
If the screens are small and/or you need to share values between them, sharing one ViewModel will be the way.