Why doesn't a mutableState variable based another mutableState variable using derivedStateOf changed in Android Jetpack Compose?

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

Why doesn't a mutableState variable based another mutableState variable using derivedStateOf changed in Android Jetpack Compose?

问题

The sortByState 是一个 mutableState 变量,resultListAllMInfo 会在 sortByState 改变时发生变化,经过测试是正常的。

而基于 resultListAllMInfototal 变量使用了 derivedStateOf 方法,我认为它始终获取到最新的值,但 totalEResult.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.

huangapple
  • 本文由 发表于 2023年5月26日 15:31:18
  • 转载请务必保留本文链接:https://go.coder-hub.com/76338571.html
匿名

发表评论

匿名网友

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

确定