如何正确使用带Transformations.switchMap的livedata获取初始数据?

How to use livedata with Transformations.switchMap correctly to get initial data?

我现在是第一次开始使用 LiveData。首先,我将所有代码放在 viewModel 中,包括在服务器中开始搜索的代码。 我这样使用 LiveData:

片段 onViewCreated()

        viewModel.changeNotifierContacts.observe(this, androidx.lifecycle.Observer { value -> value?.let {
        recyclerViewAdapter.setData(value)
    } })

这按预期工作。现在我按照 MVVM 模式添加一个存储库层。 (为此,我将联系人搜索功能移到了存储库 class) 首先,我像这样实现了 ViewModel 和存储库之间的连接:

视图模型代码:

fun getContacts(): MutableLiveData<ContactGroup> {
   return contactSearchRepository.changeNotifierContacts;
}

fun search(newSearchInput: String) {
   contactSearchRepository.searchInRepository(newSearchInput)
}

现在我读了这篇告诉我们不要像这样使用 LiveData 的文章:https://developer.android.com/topic/libraries/architecture/livedata#merge_livedata

本页示例:

class MyViewModel(private val repository: PostalCodeRepository) : ViewModel() {

private fun getPostalCode(address: String): LiveData<String> {
    // DON'T DO THIS
    return repository.getPostCode(address)
}

}

相反,我们应该使用这样的东西:

var changeNotifierContacts : LiveData<ContactGroup> = Transformations.switchMap(searchInput) {
    address -> contactSearchRepository.getPostCode(address) }

问题:

  1. 我对这篇文章的理解是否正确,或者我可以使用我的第一个实现吗?
  2. 在我的 viewModel 构造函数中,我正在创建我的存储库对象的实例,它开始观察服务器数据并获取初始数据。 (例如,我正在获取我所有朋友的列表)。如果我使用我的第一个实现,我会得到这个初始数据。如果我使用 Transformations.switchMap 实现,我不会得到这个初始数据。我首先必须在此处开始搜索以获取更新的数据。这不是我想要的,我还需要在不进行搜索的情况下显示 "my friends" 列表。
  3. 我可以在这里使用另一种方法吗?也许 LiveData 不是连接 ViewModel 和 Repository 的最佳解决方案?

感谢您的回复和建议!

Did I understand this article correctly or can I use my first implementation?

我想你做到了,但我相信你把这个概念扩展得太多了。

如果您希望用户输入搜索以获得答案,您应该按照他们说的去做:

class MyViewModel(private val repository: PostalCodeRepository) : ViewModel() {
    private val addressInput = MutableLiveData<String>()
    val postalCode: LiveData<String> = Transformations.switchMap(addressInput) {
            address -> repository.getPostCode(address) }


    fun setInput(address: String) {
        addressInput.value = address
    }
}

但是,如果您要加载默认列表,您应该像在第一个示例中那样做:

val getContact = contactSearchRepository.changeNotifierContacts

在这种情况下,您必须遵守 getContactpostalCode.

In my constructor of the viewModel I am creating an instance of my repository object that is starting to observe server data and it is getting initial data. (For example I am getting a list of all my friends). I am getting this initial data if I am using my first implementation. If I am using Transformations.switchMap implementation I am not getting this initial data. I first have to start a search here to get updated data then. This is not what I want, I also need to display "my friends" list without doing a search.

您可以使用默认搜索开始 [​​=38=],如下所示:

MyViewModel.setInput("Friends")

这样您就不需要观察两个对象,因为 postalCode 将提供所有答案。

Is there another approach I can use here? Maybe LiveData is not the best solution to connect ViewModel with Repository?

我认为实时数据就是您的答案。完成学习曲线后,它变得更容易处理!

希望对您有所帮助!