What we can do is to register a content observer for that particular content uri(contacts in this case) in our data source. Something like this:
fun registerContentObserver(): LiveData<Long> {
val changedAt: MutableLiveData<Long> = MutableLiveData(System.currentTimeMillis())
observer = object : ContentObserver(null) {
override fun onChange(self: Boolean) {
changedAt.postValue(System.currentTimeMillis())
}
}
contentResolver.registerContentObserver(ContactsContract.Data.CONTENT_URI, true, observer)
return changedAt
}
We can observe this, so that view will be notified when content has changed.
If you want to automatically update the list then in the view model you can do a switch transformation in this new livedata we created:
var myContacts: LiveData<List<MyContact>> = Transformations.switchMap(myContactsRepository.contactChangeListener) {
liveData {
emit(myContactsRepository.fetchContacts())
}
}
So whenever a content change occurs, new contacts will be fetched automatically.