每次轮换后重新加载数据我在onCreate中获取数据并在onCreateView()中观察。我想在旋转手机后知道(或者在配置更改后再次重新加载数据,因此我在旋转前有这些日志
fetchConfig ->observe
旋转后我有
observe ->fetchConfig ->observe
我怎样才能防止第二次重装数据?我在fetchConfig()中添加了
if(customerConfigData.value==null) {}
但我不确定这是最好的解决方案
private val viewModel: HomeViewModel by lazyViewModel()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
viewModel.fetchConfig()
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
viewModel.customerConfigData.observe(viewLifecycleOwner, Observer {
Log.i("test","observe")
})
return inflater.inflate(R.layout.fragment_home,container,false)
}
fun fetchConfig() {
Log.i("test","fetchConfig")
uiScope.launch {
val configEndpoint = EnigmaRiverContext.getExposureBaseUrl().append("v1/customer").append(AppConstants.CUSTOMER_UNIT)
.append("businessunit").append(AppConstants.BUSINESS_UNIT).append("defaultConfig").append("?preview=true")
val parsedData = homeRepository.fetchConfig(configEndpoint, GetConfigCall())
customerConfigMutableData.postValue(parsedData)
}
}
我认为一个解决方案是将fetchConfig()
调用到你的init
的ViewModel
块
我也有类似的问题。我被建议尝试LiveData的事件包装器,它解决了我的问题:)
这是链接:How to stop LiveData event being triggered more than Once
希望这可以帮助!
如您所见,您的方法有一个名为savedInstanceState: Bundle?
的参数。该捆绑包能够在配置更改时保存应用程序的状态。所以,你可以在这里放任何你想要的旗帜。现在,请记住ViewModels旨在通过良好的代码库实现。因此,您需要将Ui层与业务层分开。 fetch配置方法应该在另一个不依赖于Android生命周期的类中。我强烈建议阅读这些文章。
结论。您的解决方案不是最好的。最好的方法是实现一个正确的层,以便以不依赖于Android生命周期的方式获取信息。