[英]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
.在 ViewModel 我有MutableLiveData<MutableList<object>>
并且我想创建LiveData<List<object>>
,但我不知道如何从MutableList
创建List
。
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> ) (但我收到错误类型不匹配。必需:LiveData<List> 找到: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 .当我将val tasks: LiveData<List<Task>> = _tasks
为val tasks: LiveData<MutableList<Task>> = _tasks
它可以工作,但我希望任务中的List
不可编辑。
LiveData is defined in Java, where there is no declaration-site variance. LiveData 在 Java 中定义,其中没有声明站点差异。 (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: (如果它是在 Kotlin 中定义的,他们可能会让类型协变out
避免这个问题。)为了解决这个问题,您可以使用使用站点方差来使其协变:
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.协变意味着您不能从此引用中修改其内容,这对于只读 LiveData 已经是正确的。 This just makes it known to the compiler.这只是让编译器知道它。 Marking it covariant allows the the up-casting of the MutableList type to List type.将其标记为协变允许将 MutableList 类型向上转换为 List 类型。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.