我正在为我最近加入的一家公司维护一个 Android 应用程序。我正在研究的一个顽固错误是,除了第一次之外,主屏幕需要很长时间才能加载。 logcats 显示用于加载数据的 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?
尝试使用 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
}