I managed to visualize the preview of the screen, by wrapping the ViewModels's functions into data classes, like this:
@OptIn(ExperimentalLifecycleComposeApi::class)
@Composable
@ExperimentalFoundationApi
@Preview
fun VolumeSettingsScreen(
modifier: Modifier = Modifier,
speechCallbacks: SpeechCallbacks = SpeechCallbacks(),
navigationCallbacks: NavigationCallbacks = NavigationCallbacks(),
viewModelCallbacks: VolumeSettingsScreenCallbacks = VolumeSettingsScreenCallbacks()
) {
MyAppheme {
Box(
...
)
}
}
I passed not the ViewModel directly in the compose but needed functions in a Data class for example, like this:
data class VolumeSettingsScreenCallbacks(
val uiState: Flow<BaseUiState?> = flowOf(null),
val onValueUpSelected: () -> Boolean = { false },
val onValueDownSelected: () -> Boolean = { false },
val doOnBoarding: (String) -> Unit = {},
val onScreenCloseRequest: (String) -> Unit = {}
)
I made a method that generates those callbacks in the ViewModel, like this:
@HiltViewModel
class VolumeSettingsViewModel @Inject constructor() : BaseViewModel() {
fun createViewModelCallbacks(): VolumeSettingsScreenCallbacks =
VolumeSettingsScreenCallbacks(
uiState = uiState,
onValueUpSelected = ::onValueUpSelected,
onValueDownSelected = ::onValueDownSelected,
doOnBoarding = ::doOnBoarding,
onScreenCloseRequest = ::onScreenCloseRequest
)
....
}
In the NavHost I hoisted the creation of the ViewModel like this:
@Composable
@ExperimentalFoundationApi
fun MyAppNavHost(
speech: SpeechHelper,
navController: NavHostController,
startDestination: String = HOME.route,
): Unit = NavHost(
navController = navController,
startDestination = startDestination,
) {
...
composable(route = Destination.VOLUME_SETTINGS.route) {
hiltViewModel<VolumeSettingsViewModel>().run {
VolumeSettingsScreen(
modifier = keyEventModifier,
speechCallbacks = speech.createCallback() // my function,
navigation callbacks = navController.createCallbacks(), //it is mine extension function
viewModelCallbacks = createViewModelCallbacks()
)
}
}
...
}
It is a bit complicated, but it works :D. I will be glad if there are some comets for improvements.