android - 使用 SharedFlow 执行单次操作,无需转换为所需值

标签 android android-jetpack-compose android-mvvm kotlin-sharedflow

我的 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/

相关文章:

android - 如何使用数据绑定(bind)在 TextView 中连接两个整数?

android - 两个不同的 Android 应用程序具有相同 API 后端的 GAE 端点?

java - 使用 array 或 arrayList 动态添加 Circles

android - 如何在 androidTest 配置中排除或替换应用依赖项

vector - 如何在 Jetpack Compose 中设置矢量图标资源的色调?

android - 为什么必须删除作为 observeForever 添加到 LiveData 的观察者?

android - 将多个文件传递给另一个应用程序

Android Compose - 具有类似 GradientDrawable 的角度的自定义线性渐变

drop-down-menu - DropDownMenuItem 在 Android jetpack compose 中无法正常工作

当其主机 Activity 不在 Activity 堆栈的顶部并且设备旋转时,Android ViewModel 重新创建