android - Jetpack Composable 不会对更改做出反应
问题描述
我一直在努力追随我能找到的唯一一个有支持的好例子,但就我而言,它不起作用。
我有一个与 Composable 中的 aViewModel
对话,并根据 a 更改 a但它不会重新组合。@Model
loading: Bool
MutableLiveData<Boolean>
class LoaderViewModel : ViewModel() {
val loadingLiveData = MutableLiveData<Boolean>(false)
fun fetch() {
viewModelScope.launch {
val flow = flowOf("result")
.onStart {
loadingLiveData.value = true
delay(2000)
}
.onCompletion {
loadingLiveData.value = false
}
.collect {
// Do something with the result
}
}
}
}
class LoaderFragment : Fragment() {
private val viewModel: LoaderViewModel by viewModel()
@Model
class ActivityLoadingState(var loading: Boolean = false)
private val activityLoadingState = ActivityLoadingState()
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
return FrameLayout(context ?: return null).apply {
layoutParams = FrameLayout.LayoutParams(MATCH_PARENT, MATCH_PARENT)
setContent {
Loader()
}
}
}
@Composable
fun Loader() = MaterialTheme {
val loadingModel = activityLoadingState
Container {
Center {
if (loadingModel.loading) {
CircularProgressIndicator(
color = Color(0xFFFF0000)
)
} else {
Container { }
}
}
}
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
subscribeUI()
viewModel.fetch()
}
private fun subscribeUI() {
viewModel.loadingLiveData.observe(viewLifecycleOwner) {
activityLoadingState.loading = it
}
}
}
解决方案
我正在做的是在我的 ViewModel 中有 Flows,并使用函数 collectAsState() whitin 组合。
推荐阅读
- docker - Grails Gradle Docker 插件 bmuschko.github.io/gradle-docker-plugin/ throws 无法设置未知属性“env”
- jquery - 无法将行添加到 jQuery 数据表
- laravel - Laravel Nova - 表单发布前的确认对话框
- sql-server - 在 SSRS 报告中隐藏空值
- docker - docker jupyter notebook 地址从不响应/超时
- kubernetes - 无法更改类型:要键入的 ClusterIP:kubernetes 中 kube-dns 的 LoadBalancer
- symfony - 在 symfony4 表单中对 CollectionType 使用 query_builder?
- python - 如何加载和使用预置的 PyTorch InceptionV3 模型对图像进行分类
- java - 我有一个文件 abc.txt 但实际上它是 abc.java(意味着文件中有 java 代码),那么如何通过其内容获得正确的扩展名?
- php - 如何正确地将mysql中的数据放入其中
- ?