state.asStateFlow() 和 flow.stateIn() 之间有什么区别?

huangapple go评论54阅读模式
英文:

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&lt;List&lt;Chat&gt;&gt; = MutableStateFlow(emptyList())
val chats: StateFlow&lt;List&lt;Chat&gt;&gt; = _chats.asStateFlow()

init {
    viewModelScope.launch {
        repository.chatsFlow.collect { chats -&gt;
            _chats.value = chats
        }
    }
}

The second one:

val chats: StateFlow&lt;List&lt;Chat&gt;&gt; = 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.

huangapple
  • 本文由 发表于 2023年4月13日 19:39:28
  • 转载请务必保留本文链接:https://go.coder-hub.com/76004983.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定