0

以下是活动课。

class MainActivity : ComponentActivity() {

    private val viewModel: MainViewModel by viewModels { MainViewModelProvider() }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            StateExampleTheme {
                // A surface container using the 'background' color from the theme
                Surface(color = MaterialTheme.colors.background) {
                    val state by viewModel.viewStatePublisher.collectAsState()

                    when (state) {
                        is ViewState.Failure -> {
                        }
                        ViewState.InProgress -> {
                        }
                        is ViewState.Success -> {
                            val event = (state as ViewState.Success).data
                            Greeting(event, viewModel)
                        }
                    }
                }
            }
        }
    }
}

@Composable
fun Greeting(event: Event, viewModel: MainViewModel) {
    Column {
        Text(text = "Hello ${event.data}!")
        Button(onClick = {
            viewModel.updateState(event)
        }) {
            Text(text = "Click")
        }
    }

}

视图模型是

class MainViewModel : ViewModel() {
    private val _viewStatePublisher: MutableStateFlow<ViewState> =
        MutableStateFlow(ViewState.Success(Event(0)))
    val viewStatePublisher: StateFlow<ViewState> = _viewStatePublisher

    fun updateState(event: Event) {
        event.data = event.data + 1
        viewModelScope.launch {
            _viewStatePublisher.emit(ViewState.Success(newEvent))
        }
    }
}

class MainViewModelProvider : ViewModelProvider.Factory {
    override fun <T : ViewModel?> create(modelClass: Class<T>): T {
        if (modelClass.isAssignableFrom(MainViewModel::class.java)) {
            return MainViewModel() as T
        }
        throw IllegalArgumentException("Unknown ViewModel class")
    }
}

我的视图状态由

sealed class ViewState {
    data class Success(val data: Event) : ViewState()
    data class Failure(val message: String) : ViewState()
    object InProgress : ViewState()
}

并且事件类是

data class Event(var data: Int)

有了上述内容,我无法在单击按钮时更新我的​​ UI,我需要知道是否StateFlow是实现此目的的正确方法?

您可能会建议将其更改Event为以下

data class Event(val data: Int)

updateState()并将方法更新为

fun updateState(event: Event) {
        val newEvent = event.copy(data = event.data + 1)
        viewModelScope.launch {
            _viewStatePublisher.emit(ViewState.Success(newEvent))
        }
    }

但我希望data成为mutable并更新state何时data更改。

谢谢

4

1 回答 1

0

您正在尝试做的事情违背了语言设计,并且StateFlow无法判断基础数据已更改,因此它不会通知任何订阅者新数据。

我会在数据类中使用一个immutable,为什么你需要它是可变的/var?

于 2021-05-27T07:45:00.333 回答