ObjectBox 和 RecyclerView - 过滤和排序

ObjectBox & RecyclerView - Filter & Sort

将 LiveData 用于带过滤器的 RecyclerView 时,代码通常如下所示:

ViewModel.kt

private val selectedCategory = MutableLiveData<Category>()
val channels: LiveData<List<Channel>>
...
init{
channels = Transformations.switchMap(selectedCategory){ category ->
            category?.let { repository.getChannelsByCategory(category) }
        }
}

fun filterByCategory(category: Category?){
        category?.let {
            selectedCategory.postValue(category)
        }
 }

但是现在,我开始使用 ObjectBox,并且我一直使用 ObjectBoxLiveData。转换不适用于此处:

ViewModelObjectBox.kt

private val selectedCategory = MutableLiveData<Category>()
val channels: ObjectBoxLiveData<List<Channel>>
...
init{
channels = Transformations.switchMap(selectedCategory){ category ->
            category?.let { repository.getChannelsByCategory(category) } // This is not working.
        }
}

这里如何进行?

目前我使用“MediatorLiveData”解决了这个问题。 这是一个例子:

class ChannelViewModel {
...
private val selectedCategory: MutableLiveData<Category> = MutableLiveData()
val channelData = MediatorLiveData<List<Channel>>()

 init{
      channelData.addSource(selectedCategory) {
      channelData.value = this.channelRepository.getChannelsByCategory(it)
 }

  fun filterByCategory(category: Category){
        selectedCategory.value = category
    }
...
}

如果有更好的方法,我很乐意看到。