Home > Mobile >  How to use the keyword also in kotlin android
How to use the keyword also in kotlin android

Time:02-23

Am learning android kotlin follow this: https://developer.android.com/topic/libraries/architecture/viewmodel#kotlin

class MyViewModel : ViewModel() {
private val users: MutableLiveData<List<User>> by lazy {
    MutableLiveData<List<User>>().also {
        loadUsers(it)
    }
}

fun getUsers(): LiveData<List<User>> {
    return users
}

private fun loadUsers() {
    // Do an asynchronous operation to fetch users.
}
}

Dont know how to write the fun loadUsers()

Here is my User:

class User  {

 constructor(name: String?) {
      this.name = name
 }

 var name:String? = null
 }

If dont use the keyword 'also' , i know how to do it. But if use 'also' , it seems not work.

Here is how i try to write the fun loadUsers:

private fun loadUsers( it: MutableLiveData<List<User>>){
    val users: MutableList<User> = ArrayList()
    for (i in 0..9) {
        users.add(User("name$i"))
    }
    it =  MutableLiveData<List<User>>(users)
}

Error tips near it : Val cant be ressigned

CodePudding user response:

Part 1: According to the Kotlin documentation, also provides the object in question to the function block as a this parameter. So, every function call and property object you access is implied to refer to your MutableLiveData<List<User>>() object. also returns this from the function block when you are done.

Thus, another way of writing your MutableLiveData<> would be like this:

val users = MutableLiveData<List<User>>()
users.loadUsers()

Part 2: As far as how to implement loadUsers(), that is a separate issue (your question is not clear). You can use Retrofit RxJava to load the data asynchronously, and that operation is totally outside of the realm of ViewModel or also.

Part 3: With your approach, you have conflicting things going on. Instead of doing a loadUsers() from your lazy {} operation, I would remove your lazy {} operation and create a MutableLiveData<> directly. Then, you can load users later on and update the users property any time new data is loaded. Here is a similar example I worked on a while ago. It uses state flows, but the idea is similar. Also use a data class to model the User instead of a regular class. Another example.

CodePudding user response:

It is solved change to code:

private fun loadUsers( it: MutableLiveData<List<User>>){
    val users: MutableList<User> = ArrayList()
    for (i in 0..9) {
        users.add(User("name$i"))
    }
    it.value =  users
}

it can't be reassigned , but it.value could .

  • Related