英文:
Why doesn't a mutableState variable based another mutableState variable using derivedStateOf changed in Android Jetpack Compose?
问题
The sortByState 是一个 mutableState 变量,resultListAllMInfo 会在 sortByState 改变时发生变化,经过测试是正常的。
而基于 resultListAllMInfo 的 total 变量使用了 derivedStateOf 方法,我认为它始终获取到最新的值,但 total 在 EResult.LOADING 情况下只会启动一次。
我的代码有什么问题?
英文:
The sortByState is a mutableState variable, resultListAllMInfo will change when sortByState changed, it's OK after testing.
And the total variable based resultListAllMInfo using derivedStateOf method, I think it always get the latest value, but total is launched once with EResult.LOADING case.
What's wrong with my code?
var sortByState by mutableStateOf(ESortBy.START_PRIORITY)
val resultListAllMInfo: StateFlow<EResult<List<MInfo>>> by derivedStateOf {
handelMInfo.listAll(sortByState).stateIn(viewModelScope, SharingStarted.WhileSubscribed(), EResult.LOADING)
}
val total by derivedStateOf {
when (val s = resultListAllMInfo.value) {
is EResult.SUCCESS -> {
log("Success")
s.data.size
}
is EResult.ERROR -> {
log("Error")
0
}
is EResult.LOADING -> {
log("Loading")
0
}
}
}
sealed class EResult<out R> {
data class SUCCESS<out T>(val data: T) : EResult<T>()
data class ERROR(val exception: Exception) : EResult<Nothing>()
object LOADING: EResult<Nothing>()
}
答案1
得分: 2
The problem is that resultListAllMInfo is a StateFlow, not a State from compose. You call resultListAllMInfo.value inside the derivedStateOf, but that won't reevaluate when the value changes, derived state can only do that with State.
英文:
The problem is that resultListAllMInfo is a StateFlow, not a State from compose. You call resultListAllMInfo.value inside the derivedStateOf, but that won't reevaluate when the value changes, derived state can only do that with State.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论