【发布时间】:2020-01-14 15:33:33
【问题描述】:
我想使用 SearchView 搜索房间数据库中的某些元素,但我遇到了问题,因为我无法在 RecyclerViewAdapter 中使用 getFilter,因为我有 ViewModel,也许谁知道如何将所有这些元素组合到一个项目中。
我搜索一种使用 Transormations.switchMap 的方法。但我无法连接它们。
ProductViewModel
class ProductViewModel(application: Application) : AndroidViewModel(application) {
private val repository: ProductRepository
val allProducts: LiveData<List<ProductEntity>>
private val searchStringLiveData = MutableLiveData<String>()
init {
val productDao = ProductsDB.getDatabase(application, viewModelScope).productDao()
repository = ProductRepository(productDao)
allProducts = repository.allProducts
searchStringLiveData.value = ""
}
fun insert(productEntity: ProductEntity) = viewModelScope.launch {
repository.insert(productEntity)
}
val products = Transformations.switchMap(searchStringLiveData) { string ->
repository.getAllListByName(string)
}
fun searchNameChanged(name: String) {
searchStringLiveData.value = name
}
}
ProductDao
interface ProductDao {
@Insert(onConflict = OnConflictStrategy.IGNORE)
suspend fun insertProduct(productEntity: ProductEntity)
@Query("SELECT * from products")
fun getListAllProducts(): LiveData<List<ProductEntity>>
@Query("DELETE FROM products")
suspend fun deleteAll()
@Query("SELECT * FROM products where product_name_ent LIKE :name or LOWER(product_name_ent) like LOWER(:name)")
fun getListAllByName(name: String):LiveData<List<String>>
}
【问题讨论】:
标签: android kotlin viewmodel searchview