Android kotlin mvvm 更新实时数据

Android kotlin mvvm update live data

如何在 kotlin 中更新可变实时数据

以下是我在 viewModel 中的实体

 private val searchResult = MutableLiveData<Resource<SearchResult?>>()

以下是搜索结果pojo

data class SearchResult(

@field:SerializedName("Response")
val response: String? = null,

@field:SerializedName("totalResults")
val totalResults: String? = null,

@field:SerializedName("Search")
val search: MutableList<SearchItem?>? = null
)

@Entity(tableName = "searchitem")
data class SearchItem(


@ColumnInfo(name = "type")
@field:SerializedName("Type")
var type: String = "",

@ColumnInfo(name = "year")
@field:SerializedName("Year")
var year: String = "",

@ColumnInfo(name = "id")
@PrimaryKey
@field:SerializedName("imdbID")
var imdbID: String = "",

@ColumnInfo(name = "poster")
@field:SerializedName("Poster")
var poster: String = "",

@ColumnInfo(name = "title")
@field:SerializedName("Title")
var title: String = "",

@ColumnInfo(name = "isfav")
var isFav: Boolean = false



)

我想更新索引 MutableList 处的项目?从搜索结果无法做到这一点。如何更新实时数据?

你的ViewModel应该有两个值,例如

class SearchViewModel() : ViewModel() {
    private val _searchResult = MutableLiveData<Resource<SearchResult?>>()
    val searchResult: LiveData<MutableList<Resource<SearchResult?>>>
        get() = _searchResult

    fun updateItem(index: Int){
         _searchResult.value?[index] = do whatever here
         _searchResult.value = _searchResult.value
    }
}