(我是Android开发的新手,所以这可能是一个基本问题.我已经尽我所能地搜索了.)
我依赖于一个异步更新数据并在有新数据时提供回调的服务.我试图弄清楚如何使用它来更新我的UI时,数据的变化.
我已经看过了基本的Jetpack编写教程,我可以构建一个带有更新计数按钮的用户界面.基于这些知识,我想到的最好的 idea 是在ComponentActivity的init
方法中创建一个MutableState
.这是有效的,但我不知道这是否是正确的方式.
以下是我的代码(略有混淆以删除隐私细节):
class MainActivity : ComponentActivity() {
// Get the updating value from the async service
private val asyncService = getAsyncService()
private val updatingValue = asyncService.getUpdatingValue()
// Create a MutableState for the UI
private val mutableValue = mutableStateOf(updatingValue.value)
init {
// Update the MutableState whenever the value changes
updatingValue.onUpdate { newValue ->
run {
mutableValue.value = newValue
}
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
ExampleComponent(mutableValue)
}
}
}
@Composable
fun ExampleComponent(value: MutableState<String>) {
Text("The value is : ${value.value}")
}
这是正确的吗,还是有更好的方法来做到这一点?
最新情况:
我编写了一个这样的ViewModel类,它工作得很好:
class AsyncDataViewModel : ViewModel() {
private val asyncService = getAsyncService()
private val updatingValue = asyncService.getUpdatingValue()
val value = mutableStateOf(updatingValue.value)
init {
updatingValue.onUpdate { updatedValue ->
run {
value.value = updatedValue.value
}
}
}
}