以下是活动课。
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
更改。
谢谢