Convert LiveData to MutableLiveData

后端 未结 4 2051
天命终不由人
天命终不由人 2021-02-14 13:28

Apparently, Room is not able to handle MutableLiveData and we have to stick to LiveData as it returns the following error:

error: Not sure how to convert a Curso         


        
4条回答
  •  灰色年华
    2021-02-14 13:50

    If you really need to, then you can use the mediator trick.

    In your ViewModel

     val sourceProduct: LiveData() = repository.productFromDao()
     val product = MutableLiveData()
    
     val mediator = MediatorLiveData()
    
     init {
          mediator.addSource(sourceProduct, { product.value = it })
     }
    

    In fragment/activity

    observe(mediator, {})
    observe(product, { //handle product })
    

提交回复
热议问题