Android livedata doesn't observe new insert

A common issue!

LiveData in Android doesn't automatically observe new inserts in a database or a data source. This is because LiveData is designed to observe changes to a specific data source, not to automatically detect new data.

When you insert new data into a database or data source, LiveData won't automatically notify its observers. You need to explicitly notify the observers by calling setValue() or postValue() on the LiveData instance.

Here are a few ways to solve this issue:

  1. Use a MediatorLiveData: You can create a MediatorLiveData that wraps your original LiveData instance. Then, you can use the MediatorLiveData to observe the new insert and notify the observers.

    val mediatorLiveData = MediatorLiveData<List<MyData>>()
    mediatorLiveData.addSource(originalLiveData) { data ->
     // Observe new inserts here
     if (data!= null && data.size > originalLiveData.value?.size) {
         mediatorLiveData.value = data
     }
    }
  2. Use a Flowable or Observable: If you're using Room or another database library, you can use a Flowable or Observable to observe the database changes. Then, you can convert the Flowable or Observable to a LiveData instance.

    val flowable = myDatabase.myDao().getMyDataFlowable()
    val liveData = flowable.toLiveData()
  3. Use a ViewModel: If you're using a ViewModel, you can use the ViewModel to observe the new insert and notify the observers.

    class MyViewModel(private val myDao: MyDao) : ViewModel() {
     private val _myData = MutableLiveData<List<MyData>>()
     val myData: LiveData<List<MyData>> = _myData
    
     init {
         myDao.insertMyData(myData) // Observe new inserts here
     }
    }
  4. Use a Room callback: If you're using Room, you can use a callback to observe the new insert.

    
    @Dao
    interface MyDao {
     @Insert
     fun insertMyData(myData: List<MyData>)
    }

class MyViewModel(private val myDao: MyDao) : ViewModel() { private val _myData = MutableLiveData<List>() val myData: LiveData<List> = _myData

init {
    myDao.insertMyData(myData) // Observe new inserts here
}

}


Remember to always check the documentation for the specific library or framework you're using to ensure you're using the correct approach.