Android implement search with view model and live data

后端 未结 5 1653
灰色年华
灰色年华 2020-12-15 01:10

I\'m working on a project in android for a udacity course I\'m currently trying to implement a search function while adhering to android architecture components and using fi

5条回答
  •  长情又很酷
    2020-12-15 02:00

    I implement the bar code searching product using the following approach.
    Everytime the value of productBarCode changes, the product will be searched in the room db.

    @AppScoped
    class PosMainViewModel @Inject constructor(
    var localProductRepository: LocalProductRepository) : ViewModel() {
    
    val productBarCode: MutableLiveData = MutableLiveData()
    
    val product: LiveData = Transformations.switchMap(productBarCode) { barcode ->
        localProductRepository.getProductByBarCode(barcode)
    }
    
    init {
        productBarCode.value = ""
    }
    
    fun search(barcode: String) {
        productBarCode.value = barcode
    }}
    

    In activity

    posViewModel.product.observe(this, Observer {
            if (it == null) {
               // not found
            } else {
                productList.add(it)
                rvProductList.adapter!!.notifyDataSetChanged()
            }
        })
    

    for searching

    posViewModel.search(barcode) //search param or barcode
    

提交回复
热议问题