简体   繁体   中英

Kotlin, Android - How to transform MutableLiveData<MutableList< something >> to LiveData<List< something >>

in the ViewModel I have MutableLiveData<MutableList<object>> and I want to create LiveData<List<object>> , but I don't know how to create List from MutableList .

Here is what I'm trying to do:

class AppViewModel : ViewModel() {

    private val _tasks = MutableLiveData<MutableList<Task>>(mutableListOf())
    val tasks: LiveData<List<Task>> = _tasks
}

(but I'm getting error Type mismatch. Required: LiveData<List> Found: MutableLiveData<MutableList> )

When I change the val tasks: LiveData<List<Task>> = _tasks to val tasks: LiveData<MutableList<Task>> = _tasks it works, but I want the List in tasks not to be editable .

LiveData is defined in Java, where there is no declaration-site variance. (If it were defined in Kotlin, they maybe would have made the type covariant out to avoid this problem.) To get around it, you can use use-site variance to make it covariant:

val tasks: LiveData<out List<Task>> = _tasks

Covariant means you can't modify its contents from this reference, which is already true of read-only LiveData. This just makes it known to the compiler. Marking it covariant allows the the up-casting of the MutableList type to List type.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM