Home > Software engineering >  How do I initialize one LiveData object to another?
How do I initialize one LiveData object to another?

Time:04-11

The following class has a method than can load a list of users and store it in a LiveData wrapper:

class UserLoader {
    ...
    val loadedUsersLiveData: MutableLiveData<List<User>> = MutableLiveData()

    fun loadUsers() {
        ...
        val userRequest: Call<UserResponse> = userApi.loadUsers()
        userRequest.enqueue(object : Callback<UserResponse> {
            ...
            override fun onResponse(call: Call<UserResponse>, response: Response<UserResponse>) {
               ...
              loadedUsersLiveData.value = ... // assigns the list of users returned
        }
        ...
    }
}

How would I initialize the LiveData variable in my class below to the value of the one that's fetched in the class above?

class UserTableViewModel : ViewModel() {

    // TODO: initialize usersLiveData to UserLoader's loadedUsersLiveData
    val usersLiveData: LiveData<List<User>> // ??

    fun loadUsers() {
        UserLoader().loadUsers()
    }
}

CodePudding user response:

class UserTableViewModel : ViewModel() {

    private val userLoader = UserLoader()

    // TODO: initialize usersLiveData to UserLoader's loadedUsersLiveData
    val usersLiveData: LiveData<List<User>> = userLoader.loadedUsersLiveData

    fun loadUsers() {
        userLoader.loadUsers()
    }
}

CodePudding user response:

Don't directly expose mutable properties always expose immutable properties for reading the values.
on side note: you can make class UserLoader() to object if you want to safe to call it from everywhere or don't have constructor values.
LiveData is an interface but what you can do is initialize it through MutableLiveData or another LiveData of same type which in your case from UserLoader.
You can do:

     class UserTableViewModel : ViewModel() {

        private val _userLiveData = MutableLiveData<List<User>>()
        val usersLiveData: LiveData<List<User>> get() = _userLiveData // observe it in the view..

        // don't forget to call this function...
        fun updateUserList() {
            _userLiveData.value = UserLoader().loadedUsersLiveData
        }
        
        fun loadUsers() {
            UserLoader().loadUsers()
        }
    }

or


    class UserTableViewModel : ViewModel() {
        
         //observe it in view..
        val usersLiveData: LiveData<List<User>>  = UserLoader().loadedUsersLiveData
        
    }
   
        fun loadUsers() {
            UserLoader().loadUsers()
        }

  • Related