Search code examples
androidlistkotlinandroid-livedatamutablelist

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.


Solution

  • 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.