Ahmad Sattout
Ahmad Sattout

Reputation: 2476

Using Android ViewModel not working as expected

When using this code to get the devices data, it works well. But when doing any configuration change (orientation change), the loading starts again instead of delivering the already loaded data.

class DevicesViewModel(app: Application) : AndroidViewModel(app) {
    val data = DevicesLiveData()

    inner class DevicesLiveData : LiveData<List<Device>>() {
        init {
            SpecsUtils.devicesListLimit { value = it }
        }
    }
}

Am I doing something wrong? I followed some tutorial on Medium.

As I recall, ViewModel and LiveData is designed to survive configuration changes and lifecycle events, so the data should be loaded only once.

Edit

I'm aquiring the ViewModel like this

ViewModelProviders.of(this).get<DevicesViewModel>().data.observe(this, Observer {
    adapter.devices = it
})

Upvotes: 0

Views: 1246

Answers (1)

Some random IT boy
Some random IT boy

Reputation: 8457

I would need to see a bit further deep in your code, but your code is probably not working because you're passing this and you should pass this.activity to the ViewModelProvider, like so:

myviewModel = ViewModelProvider.of(this.activity).get(MyViewModel::class.java)
myviewmodel.data({this.lifecycle}, { data -> Log.d("NEWDATA", data) }

Assuming that data is a LiveData object. This should be done to every ViewModelProvider where you want to share data, for instance if you're sharing data between two different fragments that are bound to the same activity, then you should call ViewModelProvider.of(this.activity) on both of them

Upvotes: 1

Related Questions