android 在合成中使用StateFlow更改状态时,对象的属性不会更新

ogsagwnx  于 2023-03-21  发布在  Android
关注(0)|答案(1)|浏览(291)

我按照上一个Google教程在一个新项目中介绍了Compose/ViewModel/State,但是我遇到了一个我不理解的问题。当我使用Viewmodel中的一个方法将一个对象从null更新为新示例时,UI会被更新,但是当我使用相同的方法只更新这个对象的一个参数时,修改是不可见的。
这里是代码ViewModel

data class AppOscarUiState(
val selectedStep: Step? = null
)

class AppViewModel() : ViewModel(){
  private val _uiState = MutableStateFlow(AppUiState())
  val uiState: StateFlow<AppUiState> = _uiState.asStateFlow()

  fun updateSelectedStep(newStep: step){
    _uiState.update { currentState ->
        currentState.copy(selectedStep = newStep)
    }
  // also tried _uiState.value = _uiState.value.copy(selectedStep = newStep)

  }
}

在可组合的

fun CardDetail(
    appViewModel: AppViewModel
) {
    val appUiState by appViewModel.uiState.collectAsState()

   Column(
        Modifier
            .fillMaxSize()
            .padding(horizontal = 16.dp, vertical = 8.dp),
    ) {
    Text(
                    text = appUiState.selectedStep!!.status,
                )
    OutlinedButton(
                    onClick = {
                        selectedStep!!.status = 16
                        appViewModel.updateSelectedStep(selectedStep)
                    },
                ) {
                    Text(
                        stringResource(R.string.it_starts),
                    )
                }
    }

When the step is selected from a list, ```updateSelectedStep(newStep)``` from the viewmodel is called and a detail container is filled. And when I want to change a parameter, the same is done. A log in ```updateSelectedStep(newStep)``` indicates that the new value is well transmetted, and when the step is deselected and selected again, the new data is visible.
Step is a data class.

So why the modification is not instantaneous ? I have a similar method to update a boolean (not an object) which works fine.

Thanks for your help
dl5txlt9

dl5txlt91#

您将同一个对象传递给currentState.copy(selectedStep = newStep)-您可以记录对象地址来查看它-从Compose的Angular 来看,这意味着对象没有更改,因此不需要重新组合。
一种选择是将status定义为mutableStateOf,在这种情况下,您不需要使用copy更新状态:

var status by mutableStateOf(0)

但是如果你想把代码拆分成视图/数据层以获得更好的可测试性/使其更简洁,你不应该把var用于你想更新的属性,而应该在所有层上使用copy

appViewModel.updateSelectedStep(selectedStep!!.copy(status = 16))

相关问题