无法解释的重复 REST API 调用

问题描述 投票:0回答:1

我正在为我最近加入的一家公司维护一个 Android 应用程序。我正在研究的一个顽固错误是,除了第一次之外,主屏幕需要很长时间才能加载。 logcats 显示用于加载数据的 Api 调用被多次调用。

到目前为止我已经调查了以下原因:

  1. 循环代码正在观察数据并更改某些变量,从而无意中再次触发数据重新加载。但是,我也在 CPU 分析器中运行了代码,并且数据正确地从父片段流向子片段
  2. 多个片段实例可以调用 API。我用日志语句对此进行了调查:
reportGroupVM.selectedReport.observe(viewLifecycleOwner, Observer {
    binding.tvTitle.text = it.title
    LogUtil.d("EnergyConsumptionFrag", [email protected]())
    energyConsumptionVM.getSpecificReport(it.entityLinkContainer?.self?.href)
})

并获得具有不同 id 的片段:

2023-09-22 21:27:21.180  6992-6992  EnergyConsumptionFrag   dev.packagename                      D  EnergyConsumptionFragment{49abc22} (ab026b8f-bfe8-4587-8d4b-d451e46bea13) id=0x7f0a0211 EnergyConsumptionFragment}
2023-09-22 21:27:21.195  6992-6992  EnergyConsumptionFrag   dev.packagename                      D  EnergyConsumptionFragment{b12d8ca} (7a6776a6-824a-45d6-af2c-8c17207c1a43) id=0x7f0a0211 EnergyConsumptionFragment}
2023-09-22 21:27:21.210  6992-6992  EnergyConsumptionFrag   dev.packagename                      D  EnergyConsumptionFragment{96a67d1} (6f4d5392-8971-4906-9af7-94b5bf9df8fb) id=0x7f0a0211 EnergyConsumptionFragment}
2023-09-22 21:27:21.225  6992-6992  EnergyConsumptionFrag   dev.packagename                      D  EnergyConsumptionFragment{ff4a010} (45c24f6f-3ed6-4a75-ab08-d46f08523775) id=0x7f0a0211 EnergyConsumptionFragment}

...等等

唯一产生该碎片的地方是

    loadFragment(EnergyConsumptionFragment())
    
    private fun loadFragment(fragment: Fragment) {
        val transaction = childFragmentManager.beginTransaction()
    
        if (!fragment.isAdded) {
            transaction.add(R.id.layout_report, fragment, fragment.javaClass.simpleName)
        } else {
            //transaction.replace(R.id.layout_report, fragment, fragment.javaClass.simpleName)
        }
    
        transaction.commit()
    }


which seems correct.

What other possibilities can I look into? How should I go about debugging this issue?
android kotlin android-fragments mvvm android-livedata
1个回答
0
投票

尝试使用 SingleLiveEvent 而不是 LiveData:

open class SingleLiveEvent<out T>(private val content: T) {

    var hasBeenHandled = false
        private set // Allow external read but not write

    /**
     * Returns the content and prevents its use again.
     */
    fun getContentIfNotHandled(): T? {
        return if (hasBeenHandled) {
            null
        } else {
            hasBeenHandled = true
            content
        }
    }

    /**
     * Returns the content, even if it's already been handled.
     */
    fun peekContent(): T = content
}

更多信息:https://abhiappmobiledeveloper.medium.com/android-singleliveevent-of-livedata-for-ui-event-35d0c58512da

© www.soinside.com 2019 - 2024. All rights reserved.