英文:
What is the difference between state.asStateFlow() and flow.stateIn()?
问题
The first is:
第一个是:
private val _chats: MutableStateFlow<List<Chat>> = MutableStateFlow(emptyList())
val chats: StateFlow<List<Chat>> = _chats.asStateFlow()
init {
viewModelScope.launch {
repository.chatsFlow.collect { chats ->
_chats.value = chats
}
}
}
第二个是:
The second one:
val chats: StateFlow<List<Chat>> = repository.chatsFlow
.stateIn(
scope = viewModelScope,
started = SharingStarted.WhileSubscribed(5000L),
initialValue = emptyList()
)
英文:
There are two equal in my opinion constructions, which of them should be used when and what are the advantages of these methods?
The first is:
private val _chats: MutableStateFlow<List<Chat>> = MutableStateFlow(emptyList())
val chats: StateFlow<List<Chat>> = _chats.asStateFlow()
init {
viewModelScope.launch {
repository.chatsFlow.collect { chats ->
_chats.value = chats
}
}
}
The second one:
val chats: StateFlow<List<Chat>> = repository.chatsFlow
.stateIn(
scope = viewModelScope,
started = SharingStarted.WhileSubscribed(5000L),
initialValue = emptyList()
)
答案1
得分: 3
MutableStateFlow/asFlow 的方式应该避免使用。除了非常冗长之外,即使没有任何东西从中进行收集,它也会持续收集上游流,这会浪费资源。
英文:
The MutableStateFlow/asFlow way should be avoided. Aside from being very verbose, it continuously collects the upstream flow even when it doesn't have anything collecting from it, which wastes resources.
答案2
得分: 1
Viewed on a basic level, yes. They are (nearly) the same: Both of them create val chats
, which can then be further used in the ViewModel.
The key difference is val _chats
- Whilst chats
is immutable, _chats
is mutable; and if the values of _chats
change, the ones in chats
will as well, allowing you to have control over the data inside of your mutable list, whilst also being able to provide an immutable list for your ViewModel.
英文:
Viewed on a basic level, yes. They are (nearly) the same: Both of them create val chats
, which can then be further used in the ViewModel.
The key difference is val _chats
- Whilst chats
is immutable, _chats
is mutable; and if the values of _chats
change, the ones in chats
will as well, allowing you to have control over the data inside of your mutable list, whilst also being able to provide an immutable list for your ViewModel.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论