You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Composable持续重组导致加载弹窗多次重复显示问题求助

问题根源与解决方案

核心问题1:数据请求被重复触发

在VisionBoardNavigation的composable块中,boardUId?.let { homeViewModel.getBoardSectionList(it) }直接写在Composable根作用域内,每次Composable重组都会调用这个方法,导致ViewModel反复发起数据请求,进而重复发送Loading状态,弹窗持续弹出。

核心问题2:状态更新无重复过滤

ViewModel中_boardDataUiState的更新未做重复状态校验,即使相同的isLoading状态被多次发送,也会触发Composable重组,导致弹窗逻辑反复执行。


解决方案步骤

1. 修复Navigation中的请求触发逻辑

用LaunchedEffect包裹请求调用,确保仅在boardUId变化时才触发请求:

@Composable
fun VisionBoardNavigation(navController: NavHostController) {
    NavHost(
        navController = navController,
        startDestination = Screens.HomeScreen.route
    ) {
        composable(Screens.HomeScreen.route) { navBackStack ->
            val boardName = navBackStack.arguments?.getString("boardName")
            val boardUId = navBackStack.arguments?.getInt("boardUId")

            // 仅在boardUId变化时执行请求,避免重组重复触发
            LaunchedEffect(key1 = boardUId) {
                boardUId?.let { homeViewModel.getBoardSectionList(it) }
            }

            val homeUiState by homeViewModel.sectionList.collectAsState()

            HomeScreen(boardName.toString(), homeUiState)
        }
    }   
}

2. 优化ViewModel的状态更新逻辑

添加状态过滤,避免重复发送相同状态:

@HiltViewModel
class VisionBoardNameViewModel @Inject constructor(
        val getLastBoardDataUseCase: GetLastBoardDataUseCase
) : ViewModel() {
    
    private val _boardDataUiState = MutableStateFlow(BoardDataUiState())
    val boardDataUiState: Flow<BoardDataUiState> = _boardDataUiState.asStateFlow()
   
    fun getLastBoardData() = viewModelScope.launch {
        getLastBoardDataUseCase()
            // 过滤与当前状态完全一致的更新,减少不必要的重组
            .distinctUntilChanged { old, new ->
                old.isLoading == new.isLoading 
                        && old.error == new.error 
                        && old.boardData == new.boardData
            }
            .collectLatest { response ->
                when (response) {
                    is Resource.Success -> {
                        _boardDataUiState.update { currentState ->
                            currentState.copy(boardData = response.data, isLoading = false)
                        }
                    }
                    is Resource.Failure -> {
                        _boardDataUiState.update { currentState ->
                            currentState.copy(error = response.message, isLoading = false)
                        }
                    }
                    is Resource.Loading -> {
                        _boardDataUiState.update { currentState ->
                            currentState.copy(isLoading = true)
                        }
                    }
                }
            }
    }
}

3. 简化HomeScreen的弹窗逻辑

直接使用homeUiState.loading控制弹窗,去掉冗余的中间状态:

@Composable
fun HomeScreen(boardName: String = "Hey There", homeUiState: HomeScreenUIState) {
    if (homeUiState.loading) {
        Dialog(
            onDismissRequest = { },
            DialogProperties(dismissOnBackPress = false, dismissOnClickOutside = false)
        ) {
            Box(
                contentAlignment = Alignment.Center,
                modifier = Modifier
                    .size(100.dp)
                    .background(White, shape = RoundedCornerShape(16.dp))
            ) {
                CircularProgressIndicator()
            }
        }
    }
    // 其他UI内容
}

4. 优化UseCase的请求复用(可选)

如果boardDataRepository.getBoardList()是冷Flow,每次调用invoke()都会重新执行请求,可添加缓存确保请求仅执行一次:

class GetLastBoardDataUseCase @Inject constructor(
        private val boardDataRepository: BoardDataRepository
) {
    // 缓存请求结果,复用已加载的数据
    private val cachedResult = flow {
        emit(Resource.Loading())
        try {
            emit(Resource.Success(boardDataRepository.getBoardList().first()))
        } catch (e: Exception) {
            emit(Resource.Failure(e.message.toString()))
        }
    }.shareIn(
        CoroutineScope(Dispatchers.IO),
        started = SharingStarted.WhileSubscribed(5000),
        replay = 1
    )

    operator fun invoke(): Flow<Resource<BoardData>> = cachedResult
}

内容的提问来源于stack exchange,提问作者Pratik Fagadiya

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.12 02:59:53