当我在 Android Studio 中使用 Compose 时,如何知道 sealed class 的 subclass 将 return?

How can I know which the subclass of sealed class will return when I use Compose in Android Studio?

Result<out R>是一个密封的class,其中包含三个子classSuccessErrorLoading

乐趣Greeting@Composable

根据我的设计,我定义queryListResultclass,先赋值为Loading,然后是Success或者Error.

1:但是下面的代码无法编译成下面的错误信息,我的代码有什么问题吗?

2:我的设计有没有更好的方案?

编译错误

属性 委托必须有一个 'getValue(Nothing?, KProperty>)' 方法。 None 以下函数适用。*

@Composable
fun Greeting(
    name: String,
    mViewMode:SoundViewModel= viewModel()
) {
    Column() {
       //The following code cause error.  
       val queryList by produceState(initialValue = Result<Flow<List<MRecord>>>.Loading ) {
          value = mViewMode.listRecord()
       }

       when (queryList){
          is Loading -> { ...}
          is Error  -> { ...}
          is Success -> {...}
       }

    }
}       

class SoundViewModel @Inject constructor(): ViewModel()
{
    fun listRecord(): Result<Flow<List<MRecord>>>{
        return  aSoundMeter.listRecord()
    }

}
    
sealed class Result<out R> {
    data class Success<out T>(val data: T) : Result<T>()
    data class Error(val exception: Exception) : Result<Nothing>()
    object Loading : Result<Nothing>()
}

由于 queryList 有代表支持,因此它不能是最终的。
这意味着理论上,每次访问它时,它都可能具有不同的值。 kotlin 编译器对此非常悲观,并假设在选择 when 语句的 is Result.Success 分支和执行 val mydata = queryList.data 之间,queryList 的值可能有改变了。

要解决此问题,您可以将 queryList 的当前值分配给最终变量并使用该变量:

when (val currentList = queryList) {
    is Result.Error -> {}
    is Result.Loading -> {}
    is Result.Success -> {
        SomeComposable(currentList.data) //currentList is properly smart-cast to Result.Success
    }
}