- 在性能方面有什么区别?
- 在哪些场景下它提供了优势?
- 在使用 Kotlin Flow 时,使用 StateFlow 有什么好处。但是在使用 LiveData 的项目中不切换到 StateFlow 会有什么风险?
- Google 是否正在弃用 LiveData?:)
在性能方面有何区别?
老实说,我不知道,但由于它是由Kotlin和Android推动的,所以请相信它们 :)
在哪些情况下它会提供优势?
For LiveData
you are not forced to give an initial value, it may end up writing more code in init{}
; But for StateFlow
you are Forced to give an initial value (including null
), it may save your code a bit.
For LiveData
even if you give an initial value, you still need to do Null Check when you access its value
(see this), it's kind of annoying. But that's not gonna happen on StateFlow
- it will be what it should be.
For LiveData
you cannot easily, or elegantly observe data changes JUST inside ViewModel
, you are gona use observeForever()
which is also mentioned in here. But for StateFlow
it's easy, do it like following:
class FirstViewModel() : ViewModel() {
val uiScope = viewModelScope
val name = MutableStateFlow("Sam") //must have initial value
//val name = MutableStateFlow<String?>(null) //null is acceptable
init {
observeName()
}
private fun observeName() = uiScope.launch { //must run in coroutine scope
name.collect { name -> //for Fragment / Activity, use lifecycleScope.launch{}
//do your stuff
}
}
}
使用Kotlin Flow和StateFlow是有优势的。但在使用LiveData的项目中不切换到StateFlow会有什么风险?
在使用LiveData的项目中不切换到StateFlow会有什么风险呢?这就好比在使用Java的项目中不切换到Kotlin一样,你懂的 :)
Google是否已经废弃LiveData?
我想说是的,但他们可能会说还没有公开宣布 :)
//do your stuff
块不会涉及到更新UI吗?在ViewModel中如何做到这一点,既不需要将视图传递给ViewModel(违反MVVM),也不使用另一个可观察的/回调函数(那么,使用StateFlow
有什么意义呢?)。 - MattStateFlow/LiveData
并不意味着工作与 UI 相关,我可能想根据另一个 StateFlow/LiveData
的变化更新一个变量,但我不希望该变量暴露给 Fragment/Activity
。 - Sam ChenStateFlow
更新UI。我不明白StateFlow
的目的所在。它听起来与LiveData
相同,只是现在你必须在Activity/Fragment中处理你的协程(而Google本身声称这是不好的实践)。 - MattStateFlow
的好处。他唯一给出的真正论据是现在你可以将Fragment作为生命周期所有者而不是viewLifecycleOwner
进行传递。我认为这只是又一个没有任何益处的Android潮流。 - Matt