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
}
...
}

如果有更好的方法,我很想看看。

最新更新