在另一个请求中发出请求后应用变慢

App slow after making a request inside another request

我正在根据用户名使用协程发出请求,其中 returns 是 Object<Profile> 的列表,并且我正在使用该列表对每个对象发出另一个请求,然后切换和将信息传递到另一个屏幕,但这样的过程使应用程序变得非常慢,我想找到一种更好的方法或一种不让这个过程变得如此缓慢的方法。这是我的代码

从我开始这个过程的地方到应用变得超级慢的地方的片段

 emptyHomeViewModel.getPlayersListByName(text)
                emptyHomeViewModel.listOfPlayersByNameLiveData.observe(viewLifecycleOwner) { playersByName ->
                    emptyHomeViewModel.getPlayersProfileByName(playersByName)
                    emptyHomeViewModel.listOfProfilesByID.observe(viewLifecycleOwner) { profiles ->
                        if (profiles != null) {
                            val list: Array<Profile> = profiles.toTypedArray()
                            bundle = Bundle().apply {
                                putSerializable("user", list)
                            }
                            findNavController().navigate(
                                R.id.action_emptyHomeFragment_to_selectUserFragment,
                                bundle
                            )
                        }
                    }
                }

我正在执行协同程序并向 API

发出请求的 ViewModel
 fun getPlayersListByName(playerName: String) = viewModelScope.launch {
        val playersList = getPlayersByPersonaNameUseCase.getPlayersByName(playerName)
        if (playersList != null) {
            _listOfPlayersByNameLiveData.postValue(playersList)
        }
    }


 fun getPlayersProfileByName(playersByName: List<PlayerByPersonaNameItem>?) =
        viewModelScope.launch {
            var playersProfileList: ArrayList<Profile> = arrayListOf()
            if (playersByName != null) {
                for (player in playersByName) {
                    getPlayerByIDUseCase.getPlayerById(player.accountId)
                        ?.let { playersProfileList.add(it) }
                }
                _listOfProfilesByID.postValue(playersProfileList)
            }
        }

您实际上可以并行加载配置文件,防止一个接一个地加载它们,以减少加载数据的时间:

fun getPlayersProfileByName(playersByName: List<PlayerByPersonaNameItem>?) =
    viewModelScope.launch {
        val playersProfileList: List<Profile> = playersByName?.map { player ->
            async {
                getPlayerByIDUseCase.getPlayerById(player.accountId)
            }
        }.awaitAll().filterNotNull()
        _listOfProfilesByID.postValue(playersProfileList)
    }

您还可以通过删除额外的 LiveData 观察者并在获得 playersList:

后立即调用 getPlayersProfileByName 来稍微改进它
fun getPlayersListByName(playerName: String) = viewModelScope.launch {
    val playersList = getPlayersByPersonaNameUseCase.getPlayersByName(playerName)
    getPlayersProfileByName(playersList)
}