I.S
I.S

Reputation: 2053

How I can prevent reloading data second time after configuration change using ViewModel?

Reloading data after every rotation I fetch data in onCreate and observe in onCreateView(). I want to know after rotating the phone(or after configuration changes data is reloaded again as a result I have these logs before rotation

fetchConfig ->observe 

and after rotating I have

observe ->fetchConfig ->observe

How I can prevent reloading data second time? I have added in fetchConfig()

if(customerConfigData.value==null) {} 

but I am not sure is it the best solution

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)
}

}

Upvotes: 2

Views: 1283

Answers (3)

As you can see, your method has a parameter called savedInstanceState: Bundle?. This bundle is able to save the state of the app when the configuration changes. So, you can put here any flag you want. Now, remember that ViewModels are designed to be implemented with a good code base. So, you need to separate the Ui layer from the business layer. The fetch configuration method should be in another class which doesn't depend on the Android lifecycle. I strongly recommend reading these articles.

https://medium.com/androiddevelopers/viewmodels-persistence-onsaveinstancestate-restoring-ui-state-and-loaders-fc7cc4a6c090

https://developer.android.com/jetpack/docs/guide

In conclusion. Your solution is not the best. The best approach is to implement a correct layer for fetching the info in a way that it doesn't depend on the Android lifecycle.

Upvotes: 1

Ningan
Ningan

Reputation: 171

I too had similar issue. I was suggested to try Event wrapper for LiveData, it had solved my problem:)

Here's the link: How to stop LiveData event being triggered more than Once

Hope this helps!

Upvotes: 0

John O'Reilly
John O'Reilly

Reputation: 10350

One solution I think would be to move call to fetchConfig() in to the init block of your ViewModel

Upvotes: 3

Related Questions