android - Prevent LaunchedEffect from re-running on configuration change
问题描述
I want to run the code only once when the composable is loaded. So I am using LaunchedEffect with key as true to achieve this.
LaunchedEffect(true) {
// do API call
}
This code is working fine but whenever there is any configuration change like screen rotation this code is executed again. How can I prevent it from running again in case of configuration change?
解决方案
最简单的解决方案是存储有关您是否使用 进行 API 调用的信息rememberSaveable
:当配置更改时,它将生效。
var initialApiCalled by rememberSaveable { mutableStateOf(false) }
if (!initialApiCalled) {
LaunchedEffect(Unit) {
// do API call
initialApiCalled = false
}
}
这种方案的缺点是,如果在 API 调用完成之前配置发生变化,LaunchedEffect
协程会被取消,你的 API 调用也会被取消。
最干净的解决方案是使用视图模型,并在内部执行 API 调用init
:
class ScreenViewModel: ViewModel() {
init {
viewModelScope.launch {
// do API call
}
}
}
@Composable
fun Screen(viewModel: ScreenViewModel = viewModel()) {
}
官方文档推荐像这样传递视图模型作为参数。在产品代码中,您不需要将任何参数传递给该视图,只需将其称为Screen()
:视图模型将由默认viewModel()
参数创建。如本答案所示,它已移至测试/预览功能的参数。
推荐阅读
- uiview - 如何进行重复与连续动画?
- gitlab - 如何将秘密令牌添加到特定 gitlab 组的所有项目?
- typescript - Angular 5 需要计算组件中的属性
- python - 将带有自定义度量函数的 keras 配置保存到 JSON
- android - Android:如何将 AsyncTaskLoader 添加到此 RecyclerView
- r - 如何自定义两个因素的X轴和基于两个因素的彩条
- java - 如何知道我点击了哪个标签 [Java]
- r - 如何从R中字符串的开头删除特殊字符
- amazon-web-services - 在 Lambda 函数的内联代码属性中引用 CloudFormation 模板中的资源
- kubernetes - 在可能缩小时防止杀死一些豆荚?