如何使用 Hilt 和 Compose 在运行时将参数传递给 ViewModel 的构造函数

How to pass arguments to ViewModel's constructor at runtime using Hilt and Compose

提问人:Javier Cancio 提问时间:11/6/2023 更新时间:11/6/2023 访问量:71

问:

我正在使用 Jetpack Compose 和 Hilt for DI 开发一个应用程序。我的 ViewModel 实际上有一个注入的用例,但我需要在运行时传递一个额外的参数。我的可组合视图是 .我需要将此对象传递给我的视图模型,以便运行网络调用以根据对象 ID 获取数据。ModalBottomSheet

这是我的可组合视图

@Composable
fun StopTimesMapScreen(
    modifier: Modifier = Modifier,
    stop: Stop,
    onDismissListener: (() -> Unit),
    viewModel: StopTimesMapViewModel = hiltViewModel()
) {
    val sheetState = rememberModalBottomSheetState(skipPartiallyExpanded = true)

    val uiState by viewModel.uiState.collectAsStateWithLifecycle()

    ModalBottomSheet(
        modifier = modifier,
        onDismissRequest = onDismissListener,
        sheetState = sheetState
    ) {
        StopEstimations(status = uiState.status, estimations = uiState.estimations)
    }
}

还有我的视图模型

@HiltViewModel
class StopTimesMapViewModel @Inject constructor(
    val getStopTimesUseCase: GetStopTimesUseCase
): ViewModel() {

    private val _stop = MutableStateFlow<Stop?>(null)

    private val _estimations = MutableStateFlow<Resource<List<StopEstimation>>>(Resource.loading())

    val uiState: StateFlow<StopTimesMapUIState> = combine(_stop, _estimations) { stop, estimations ->
        StopTimesMapUIState(
            name = "${stop?.id} - ${stop?.name}",
            estimations = estimations.data ?: emptyList(),
            status = estimations.status
        )
    }.stateIn(
        scope = viewModelScope,
        started = WhileUiSubscribed,
        initialValue = StopTimesMapUIState()
    )

    fun loadStop(stop: Stop) {
        _stop.value = stop

        viewModelScope.launch {
            getStopTimesUseCase(stop.id)
                .collect { estimations ->
                    _estimations.value = estimations
                }
        }
    }
}

我需要的是将对象传递给 VM 的构造函数,以便我可以处理非可选的 flowable 以及调用 .StopStoploadStopinit

Android Kotlin MVVM android-jetpack-compose 匕首-刀柄

评论

1赞 VishnuPrabhu 11/6/2023
使用辅助注射 dagger.dev/dev-guide/assisted-injection.html
0赞 VishnuPrabhu 11/6/2023
试试这个 medium.com/scalereal/...

答: 暂无答案