【问题标题】:MutableStateFlow not recompose when list is clear in jetpack compose当 jetpack compose 中的列表清晰时,MutableStateFlow 不会重组
【发布时间】:2022-11-25 18:00:59
【问题描述】:

我有一个 MutableStateFlow,有点像 emptyList。当我添加项目时,我的视图会毫无问题地重新组合。现在我想在列表清晰时重新组合视图。我尝试了一些代码但没有任何反应。

配对视图模型

class PairViewModel : BaseViewModel() {
     val scanLowEnergyDevices by lazy { MutableStateFlow(emptyList<ScanResult>()) }

     fun addDevices(result: ScanResult) {
        scanLowEnergyDevices.value += result
    }
}

内容有状态

@Composable
fun ContentStateful(
    context: Context = LocalContext.current,
    viewModel: BloodPressurePairViewModel = getViewModel()
) {
    val activity = context as ComponentActivity
    val scanDeviceList by viewModel.scanLowEnergyDevices.collectAsStateWithLifecycle()
  
    ContentStateLess(
        scanDeviceList = scanDeviceList,
        resetAction = {
            viewModel.scanLowEnergyDevices.value.toMutableList().clear()
        }   
    )
}

ContentStateLess

@Composable
fun ContentStateLess(
    scanDeviceList: List<ScanResult>,
    resetAction: () -> Unit,
) {
    AnimatedVisibility(visible = scanDeviceList.isNotEmpty()) {
        Text(text = "scanDeviceList ${scanDeviceList.size}")
        Button(onClick = { resetAction() }) {
            Text(text = "Reset")
        }
    }
}

这里有什么问题?谢谢

【问题讨论】:

    标签: android kotlin android-jetpack-compose kotlin-flow mutablestateof


    【解决方案1】:

    尝试像这样使用SnapshotStateList

    val scanLowEnergyDevices by lazy { mutableStateListOf<ScanResult>() }
    

    添加这样的项目

    fun addDevices(result: ScanResult) {
        scanLowEnergyDevices.add(result)
    }
    

    并像处理这样的标准集合一样清除列表

    myViewModel.scanLowEnergyDevices.clear()
    

    或者在你的用例中,因为它包装在一个状态中,只需在 .add().clear() 调用之前调用 .value

    【讨论】:

      猜你喜欢
      • 2023-01-04
      • 1970-01-01
      • 2021-07-07
      • 2021-12-11
      • 2021-06-01
      • 1970-01-01
      • 2022-11-17
      • 1970-01-01
      • 2022-11-25
      相关资源
      最近更新 更多