当前位置: 首页 > 知识库问答 >
问题:

LiveData可以通过每次返回一个新的LiveData的存储库函数从UI刷新?

许正平
2023-03-14

我在repository类中有一个方法如下所示,它从本地数据库或从网络返回国家列表作为LiveData:

fun loadCountries(): LiveData<Resource<List<Country>>> {
    return object : NetworkBoundResource<List<Country>, List<CountryResponse>>() {
        ...
    }.asLiveData()
}

在ViewModel中,我有一个LiveData来保存返回的LiveData:

class CountryViewModel : ViewModel() {

    val countryListResource: LiveData<Resource<List<Country>>> = countryRepository.loadCountries()

    fun refresh() {
        // How to assign new LiveData returned by countryRepository.loadCountries() here?
        // SwitchMap needs other LiveData to be used.
    }
}

用户应该能够刷新数据,这就是我的问题出现的地方。我需要将CountryRepository.LoadCountry()返回的新LiveData注入到CountryListResource中,我不知道如何实现这一点?

有没有其他方法可以做到这一点?

共有1个答案

费秦迟
2023-03-14

解决方法很简单。首先,在您的repository类中,创建country List类型的可变(例如obj1)和不可变(例如obj2)活动数据对象。Obj2是用Obj1初始化的。那么loadCountry()函数应该只更新Obj1。

您的视图模型应该使用observeForever()来观察obj2。然后,视图模型也要创建两个与repo相同的obj,如obj3和obj4。在活动中注意obj4。Obj3正在使用ObserveForever()中的PostValue()进行更新,它反过来更新obj4(用Obj3初始化)。

希望这对你有帮助。

// obj1
private val _countryLiveData : MutableLiveData<List<Country>>

// obj2
val countryLiveData : LiveData<List<Country>>
        get() = _countryLiveData

fun loadCountries() {
    val list = fetchCountryList()
    _countryLiveData.postValue(list)
}
// obj3
private val _countryLiveData : MutableLiveData<List<Country>> 

// obj4  live data to be observed in activity
val countryLiveData : LiveData<List<Country>> 
    get() = _countryLiveData

init {

countryRepository.countryLiveData.observeForever { countryList ->
         this._countryLiveData.postValue(countryList)
   }
}

fun refresh() {
    countryRepository.loadCountries()  
}
 类似资料:
  • 此示例存储库有一个方法 现在不需要使用Robolectric来单元测试了吗?

  • 在viewmodel类中获取数据方法

  • 问题内容: MySql存储过程/函数可以在不使用临时表的情况下返回表吗? 创建以下过程 然后用 显示示例表-正如预期的那样-但似乎无法进行以下操作: 是否可以从存储过程/函数中返回查询结果表,如果可以,怎么办? 问题答案: 就目前而言,这是不可能的。 以下是该子句中可能使用的 文档: 如您所见,存储过程不在此列表中。

  • 在livedata的observe方法中有这样一条评论 在给定所有者的生命周期内将给定的观察者添加到观察者列表中。事件在主线程上分派。如果LiveData已经有数据集,它将传递给观察者。 当我尝试向现有livedata实例添加新的观察者时,如果livedata具有数据集,则new观察者的onChanged方法调用。 有什么办法可以避免这种行为吗?我只是不想被通知新的观察员 SingleLiveEv

  • 因此,我使用LiveData和ViewModel设置获取和插入数据的功能,并使用Room数据库保存数据。 将数据插入数据库后,我的RecyclerView不会更新数据。 RecyclerAdapterTransaksi.kt 使用RecyclerView显示数据库数据的片段 Pemasukkanframent。kt 使用LiveData的ViewModel类 TransaksiViewModel.

  • 我正在寻找处理下面的用例W.R.T.的建议。LiveData处理:ViewModel为LiveData调用存储库(例如产品目录)。存储库首先从LocalDataSource(Room)进行检查,但如果数据不可用,则调用RemoteDataSource(REST API)。 问题: 2)由于RemoteDataSource返回的数据不是LiveData类型,应该做些什么才能使存储库最终将LiveDa