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.
}
}
Am trying to implement this way and its not compiling :
class MyViewModel : ViewModel() {
private val users: MutableLiveData<List<String>> by lazy {
return MutableLiveData().also {
loadUsers()
}
}
fun getUsers(): LiveData<List<String>> {
return users
}
private fun loadUsers() {
users.postValue(listOf("Tarun", "Chawla"))
}
}
Mostly am not understanding the by lazy here. The example on android website seems wrong as loadUsers() is not returning anything which can be a delegate for users. can you please help me understanding above piece of code.
=======================================================
This is how I implemented:
private val users : MutableLiveData<List<String>> by lazy {
MutableLiveData<List<String>>().also {
loadUsers(it)
}
}
init {
Log.e("Tarund", "View Model created")
}
override fun onCleared() {
super.onCleared()
Log.e("Tarund", "View Model deleted")
}
fun getUsers(): LiveData<List<String>> {
return users
}
private fun loadUsers(users : MutableLiveData<List<String>>) {
users.postValue(listOf("Tarun", "Chawla"))
}
}
But if anyone can confirm if first example code above which I copy pasted from : https://developer.android.com/topic/libraries/architecture/viewmodel#kotlin is wrong
also
scoping function output is context object. thus, if first accessusers
property then returnMutableLiveData()
and callloadUsers
function – Discernible