Reputation: 745
When using LiveData for the RecyclerView with filters, the code looks usually like this:
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)
}
}
But now, I started using ObjectBox and I stuck here with the ObjectBoxLiveData. The Transformations are not applicable here:
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.
}
}
How to proceed here?
Upvotes: 0
Views: 151
Reputation: 745
For the moment I solved this using the "MediatorLiveData". Here is an example:
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
}
...
}
If there is a better way, I'd love to see it.
Upvotes: 0