与JetPack一起使用MutableState时的最佳实践,并在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组成的MutableState的最佳实践是什么。
I have the following 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()
}
I never expose mutableStateFlow as in the example above. And SonarLint will show a warning when doing this.
MutableStateFlow" and "MutableSharedFlow" should not be exposed
So I apply the same technique to the mutableState
However, If I do like this below, I don't get any warning.
val searchAppBarStateMutableState: MutableState<SearchAppBarState> = mutableStateOf(SearchAppBarState.CLOSED)
Just wondering what is the best practice for using MutableState with jetpack compose.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
要将MutableState与ViewModel一起使用,请用私有设置器在ViewModel内定义MutableState,例如,
通过上述,我们可以从ViewModel外部读取可变状态,但不能更新它。要更新在ViewModel内部创建公共功能,例如 -
通过制作一个设置器函数,我们正在遵循关注点的分离,并具有一个真实的来源来编辑mutableState。
To use mutableState with viewmodel, define mutableState with private setter inside viewmodel, ex -
By doing above we can read the mutable state from outside of viewmodel but not update it. To update create a public function inside viewmodel, ex -
By making a setter function we are following separation of concerns and having a single source of truth for editing the mutableState.
我认为错误是您要设置的
如果要共享私人价值,则您不应该将其设置为平等,而是可以使用Get Modifier,
也最好使用下划线命名,因为许多开发人员都习惯了喜欢:
I think the error is in that you are setting
if you want to share private value as not mutable you shouldn't set it equal rather you can use get modifier
Also it would be better to name it with underscore as many developers are used to like: