Ellen Spertus
03/10/2020, 5:27 PMViewModel
for my state. Could anyone advise me how to adapt the https://developer.android.com/topic/libraries/architecture/viewmodel example to support the case where an argument needs to be passed into getUsers()
and through to loadUsers()
for it to do its job?
class MyViewModel : ViewModel() {
private val users: MutableLiveData<List<User>> by lazy {
MutableLiveData().also {
loadUsers()
}
}
fun getUsers(): LiveData<List<User>> {
return users
}
private fun loadUsers() {
// Do an asynchronous operation to fetch users.
}
}
I could store the information in an instance variable from getUsers()
and retrieve it from loadUsers()
, but that doesn’t seem very nice.
What I need to pass in is a Context
(to access assets and the package manager). I don’t cache the Context.Ellen Spertus
03/10/2020, 5:34 PMContext
from a ViewModel
. Is this the way to go?
https://stackoverflow.com/a/56490520/631051Alan Donizete
03/10/2020, 5:47 PMAlan Donizete
03/10/2020, 5:48 PMEllen Spertus
03/10/2020, 5:48 PMMainActivity
gets destroyed?Ellen Spertus
03/10/2020, 5:49 PMAdam Powell
03/11/2020, 2:02 AMContext
for? If you can keep the ViewModel working only in terms of Context
-insensitive data you can mix in the additional asset loading at the last mile with something like a .map {}
of the users LiveData from your exampleAnastasia Finogenova
03/11/2020, 2:17 AMAdam Powell
03/11/2020, 2:21 AMConfiguration
set up, so depending what kind of resources or assets you're loading, it's an easy way to get the wrong thingAdam Powell
03/11/2020, 2:22 AMAndroidViewModel
base class to get it without additional injection if you're not already using a DI systemAnastasia Finogenova
03/11/2020, 2:23 AMAnastasia Finogenova
03/11/2020, 2:25 AM