0

我有一个像这样的密封类

sealed class LoadState {
    class Loading : LoadState()
    class Success : LoadState()
    class Fail : LoadState()
}

我将密封类与 LiveData 一起使用,它可以工作

open class BaseViewModel: ViewModel() {
//    val loadState by lazy {
//        MutableLiveData<LoadState>()
//    }
    val loadState by lazy {
        MutableStateFlow(LoadState())
    }
}

但是当我将 MutableLiveData 更改为 MutableStateFlow 时,我收到这样的警告

Sealed types cannot be instantiated

那么,如何在 MutableStateFlow 中使用密封类?

4

2 回答 2

1

对于使用带有密封类的 MutableStateFlow,您可以执行以下操作: 第 1 步:创建一个密封类。

sealed class LoadState {
    object Loading : LoadState()
    object Success : LoadState()
    object Fail : LoadState()
}

然后按以下方式使用它们


    private val mutableStateFlow : MutableStateFlow<LoadState?> = MutableStateFlow(null)
    val stateFlow : StateFlow<LoadState?> get() = mutableStateFlow

您可以通过以下方式监听 mutableStateFlow。在片段的 OnViewCreated 中:

viewLifecycleOwner.lifecycleScope.launch {
            repeatOnLifecycle(Lifecycle.State.STARTED) {

                viewModel.stateFlow.collect { viewState ->
                    when (viewState) {
                       is Loading ->{//do something}

                       is Success ->{//do something}

                       is Fail->{//do something}
                       
                    }
                }
            }
        }

这样你就不需要每次都指定一个初始方法。这就是你如何使用带有 mutableState Flow 的密封类

于 2021-08-19T10:13:01.013 回答
0

你必须选择你的initial state

open class BaseViewModel: ViewModel() {
    val loadState by lazy {
        MutableStateFlow(LoadState.Loading()) <-- for example, initial is loading
    }
}

并且,data class在密封类中使用。

sealed class LoadState {
    data class Loading() : LoadState()
    data class Success() : LoadState()
    data class Fail() : LoadState()
}
于 2021-08-19T09:46:29.263 回答