android - 可以使用每次返回新 LiveData 的存储库功能从 UI 刷新 LiveData?

标签 android mvvm android-livedata

我在存储库类中有一个方法如下,它从本地数据库或网络返回国家列表作为 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.loadCountries() 返回的新 LiveData 注入(inject)到 countryListResource 中,我不知道如何实现?

如果我执行 countryListResource = countryRepository.loadCountries()(我不能这样做,因为它是 val),观察者需要停止观察前一个并开始观察最新的一个。

如果我在 countryListResource 上使用 swichMap,我需要另一个 MutableLiveData 来触发来自存储库的新调用,如图所示 here .

还有其他方法可以实现吗?

最佳答案

解决方法很简单。 首先在你的存储库类中创建可变的 obj1 和不可变的 obj2 类型国家列表的实时数据对象。 Obj2 用 obj1 初始化。然后 loadCountry() 函数应该只更新 obj1。

您的 View 模型应该使用 observeForever() 观察 obj2。 然后 View 模型也创建两个与 repo 相同的 obj 说 obj3 和 obj4 resp。观察 Activity 中的 obj4。 Obj3 正在使用 observeForever() 中的 postValue() 进行更新,然后更新 obj4(使用 obj3 初始化)。

希望对你有帮助。

示例:

Repository

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

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

fun loadCountries() {
    val list = fetchCountryList()
    _countryLiveData.postValue(list)
}

ViewModel

// 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()  
}

关于android - 可以使用每次返回新 LiveData 的存储库功能从 UI 刷新 LiveData?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57984348/

相关文章:

c# - 将 WinForm 应用程序转换为 WPF ViewModel

android - 将 PagedListAdapter 与 LiveData 一起使用时如何显示空 View ?

java - LiveData、Transformations.map() - 如何在用户更改过滤顺序时强制刷新?

android - gitignore android 包含 apk

c# - 真正的 MVVM 和第三方控件

c# - ViewModel 类应该实现 INotifyPropertyChanged 还是我可以使用对象组合?

android - LiveData 无法通知它的观察者 PagedList 对象的变化

android - ActionBarSherlock 不确定的进度指示器不会在模拟器中消失

android - 从最近的应用程序列表中删除时,我的应用程序被杀死

android - ViewPager2 |未调用 View.ClickListener