首页 > 解决方案 > 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?

标签: androidkotlinandroid-jetpack-composeandroid-jetpack

解决方案


最简单的解决方案是存储有关您是否使用 进行 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()参数创建。如本答案所示,它已移至测试/预览功能的参数。


推荐阅读