我的 View 模型中有以下 SharedFlow -
class HeroesViewModel(private val heroesRepositoryImpl: HeroesRepositoryImpl) : ViewModel() {
private val _uiState = MutableStateFlow(UiState())
val uiState = _uiState.asStateFlow()
private val _uiAction = MutableSharedFlow<UiAction>()
val uiAction = _uiAction.asSharedFlow()
sealed class UiAction {
data class NavigateToHeroesDetails(val heroModel: HeroModel) : UiAction()
}
我在我的可组合屏幕中实现了对它的观察 -
fun DashboardScreen(
navigator: DestinationsNavigator,
viewModel: HeroesViewModel = get()
) {
val uiState by viewModel.uiState.collectAsState()
val uiAction by viewModel.uiAction.collectAsState(initial = null)
when (uiAction) {
is HeroesViewModel.UiAction.NavigateToHeroesDetails -> {
navigator.navigate(HeroDetailsScreenDestination(uiAction.heroModel)) // Here is where I get the compiler error
}
null -> Unit
}
当尝试使用操作中的信息时,编译器给出以下错误 -
智能转换为“HeroesViewModel.UiAction.NavigateToHeroesDetails”是不可能的,因为“uiAction”是一个具有开放或自定义 getter 的属性
验证变量确实是我想要的类型的正确方法是什么?
最佳答案
因此,帮助我实现目标的答案是使用 LaunchedEffect
block 启动一个协程,并在其中收集最新的 UI 操作 -
LaunchedEffect(key1 = "") {
viewModel.uiAction.collect { uiAction ->
when (uiAction) {
is HeroesViewModel.UiAction.NavigateToHeroesDetails -> {
navigator.navigate(HeroDetailsScreenDestination(uiAction.heroModel))
}
}
}
}
关于android - 使用 SharedFlow 执行单次操作,无需转换为所需值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73558126/