我有以下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)
只是想知道在jetpack compose中使用MutableState的最佳实践是什么。
要在viewmodel中使用mutableState,请在viewmodel中使用private setter定义mutableState,例如-
var isVisible by mutableState(false)
private set
通过以上操作,我们可以从视图模型外部读取可变状态,但不更新它。要在视图模型中更新创建一个公共函数,请执行-
fun setVisibility(value: Boolean) {
isVisible = value
}
通过创建setter函数,我们遵循了关注点分离,并且在编辑mutableState时拥有单一的事实来源。
我认为错误在于您设置了
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