将 mutableState 与 Jetpack 一起使用时的最佳实践在视图模型中组合并公开可变状态

Best practice when using mutableState with jetpack compose inside viewmodel with exposing mutable state

我有以下 ViewModel

@HiltViewModel
class ShareViewModel @Inject constructor(
    private val taskRepository: TaskRepository
): ViewModel() {

    private val searchAppBarStateMutableState: MutableState<SearchAppBarState> = mutableStateOf(SearchAppBarState.CLOSED)
    val searchAppBarState: State<SearchAppBarState> = searchAppBarStateMutableState

    private val listOfTaskMutableStateFlow = MutableStateFlow<List<TodoTaskEntity>>(emptyList())
    val listOfTaskStateFlow = listOfTaskMutableStateFlow.asStateFlow()
}

我从不像上面的例子那样公开 mutableStateFlow。并且 SonarLint 会在执行此操作时显示警告。

MutableStateFlow" and "MutableSharedFlow" should not be exposed

所以我将相同的技术应用于 mutableState

但是,如果我在下面这样做,我不会收到任何警告。

val searchAppBarStateMutableState: MutableState<SearchAppBarState> = mutableStateOf(SearchAppBarState.CLOSED)

只是想知道将 MutableState 与 Jetpack Compose 结合使用的最佳实践是什么。

我认为错误在于您正在设置

    val searchAppBarState: State<SearchAppBarState> = searchAppBarStateMutableState

如果你想共享私有值作为不可变的,你不应该将它设置为相等,而你可以使用 get 修饰符

    val searchAppBarState: State<SearchAppBarState> get() = searchAppBarStateMutableState

另外,很多开发者都喜欢用下划线来命名:

    private val _searchAppBarState: MutableState<SearchAppBarState> = mutableStateOf(SearchAppBarState.CLOSED)
    val searchAppBarState: State<SearchAppBarState> get() = _searchAppBarState

要将 mutableState 与 viewmodel 一起使用,请在 viewmodel 中使用私有 setter 定义 mutableState,ex -

var isVisible by mutableState(false)
    private set

通过上面的操作,我们可以从视图模型外部读取可变状态,但不能更新它。要更新在 viewmodel 中创建一个 public 函数,ex -

fun setVisibility(value: Boolean) {
    isVisible = value
}

通过制作 setter 函数,我们遵循关注点分离并拥有用于编辑 mutableState 的单一事实来源。