0

I am trying to observe Item data changes in a List using LiveData. But for some reason it is not working as expected.

ViewModel

@HiltViewModel
class TestScreenViewModel @Inject constructor(private val repository: TestRepository) :
    ViewModel() {

    val _orderItems: LiveData<List<OrderItem>> = repository.getAllTestOrder().asLiveData()
    val orderItems: LiveData<List<OrderItem>> = _orderItems


    fun addOrderItem() {
        val item = OrderItem(name = "Order 1", price = 50, qty = 2)
        viewModelScope.launch {
            repository.addOrder(item)
        }

    }

    fun deleteAll() = viewModelScope.launch { repository.deleteAll() }

    fun changeValueOfItem() {
        _orderItems.value!![0].addQty()
    }

}

OrderItem


@Entity(tableName = "orders")
data class OrderItem constructor(

    @PrimaryKey(autoGenerate = true)
    @NonNull
    val id: Int=0,

    var name: String = "",

    var price: Int = 0,

    var imageUrl: String = "",

    var qty: Int = 0
) {
    fun addQty() {
        qty++
    }

    fun removeQty() {
        qty--
    }

    fun updateQty(q: Int) {
        qty = q
    }
}

During fun changeValueOfItem() call I just updated the qty by 1.

I already have a observable for orderItems in my Fragment but the changes are not detected.

What I am doing wrong here? Or Is there any other way to implement this scenario?

1 Answers1

0

Faced similar behavior some time ago.

For it to work properly you need to actually return LiveData from your database like this:

//your DAO
@Query(select * from smth)
fun getAllTestOrder(): LiveData<List<OrderItems>>

And also remove .asLiveData() in your ViewModel and instead do something like this

val _orderItems = repository.getAllTestOrder()
val orderItems: LiveData<List<OrderItem>> = _orderItems
Dwane13
  • 190
  • 1
  • 2
  • 8
  • Actually I am not changing the value inside the Database. I am just changing the local list "_orderItems", If I change any value inside the Database I get the update in my observable. But I trying to observe when changes are made directly in the List. If you look closely you can see I am making changes to the local "_orderItems" inside "fun changeValueOfItem". – user1418628 Sep 22 '21 at 12:47