OiO.lk Blog Android To pass or not to pass a viewmodel to a composable
Android

To pass or not to pass a viewmodel to a composable


According to the Googles own Architcture-sample they use the viewmodel as a input variable to the Composable.

@OptIn(ExperimentalLifecycleComposeApi::class)
@Composable
fun TaskDetailScreen(
    onEditTask: (String) -> Unit,
    onBack: () -> Unit,
    onDeleteTask: () -> Unit,
    modifier: Modifier = Modifier,
    viewModel: TaskDetailViewModel = hiltViewModel(),
    scaffoldState: ScaffoldState = rememberScaffoldState()
) {....}

According to Googles own guidelines they say you shouldn’t pass the ViewModel instances down to other composable functions.

Why pass and connect the viewmodel to the Composable in the first place?

Wouldn’t it be more clean to connect the viewmodel to the compose UI screen with one upstream and one downstream instead?

@Composable
fun TestScreen(
    uiState: AppUIState,
    onEvent: (AppViewEvent) -> Unit,
) {....}
TestScreen(
    uiState = viewModel.uiState.collectAsState().value,
    onEvent = viewModel::onEvent
) {....}
class MyViewModel() : ViewModel() {
    private val _uiState: MutableStateFlow<AppUIState> = MutableStateFlow(AppUIState())
    val uiState: StateFlow<AppUIState> = _uiState.asStateFlow()
    
    fun onEvent(event: AppViewEvent) {....}
}
sealed interface AppUIState {
    object DoSomething: AppUIState
    data class KeyPressed(val key: String) : AppUIState
}



You need to sign in to view this answers

Exit mobile version