0

I am using liveData in my application. I do a DB Query which returns a LiveData<PagedList<Contact>> of contacts stored in DB.

I want to modify this livedata before giving it to observers. Suppose there are ten contacts in the LiveData list, i want to do some comparison with another list and set which contacts are primary in the LiveData list.

After doing this i want to give it to observers .

e.g -

val allContacts: LiveData<PagedList<Contact>> = getFromDB()

val list: ArrayList<String>() = list of some primary contacts

traverse allContacts and list and set which values in allContacts match the values in list. which ever values in allContacts match, their isPrimary property will be set to true.

Now after modifying allContacts, i want to submit it to observers like:

allContacts.observe(this, Observer(adapter::submitList))

I tried LiveData.transform, But not able to use it properly.Can anyone suggest me how to achieve it using transform method or some other way.

Pardeep Kumar
  • 900
  • 1
  • 14
  • 30

2 Answers2

0

What you are looking for is a Transformation. Use Transformations.map() to create a new LiveData from a function that will be run everytime the first LiveData changes.

e.g.

val allContacts: LiveData<PagedList<Contact>> = getFromDB()
val contactViewModel = Transformations.map(allContacts, {
    // Transform and create new list from old
})
deive
  • 862
  • 7
  • 19
0

Your problem is rooted in the fact that you wish to "intercept" the updates that will be posted to the LiveData object by the DB. Regardless if this is a good approach you can technically achieve it by wrapping the LiveData that is returned by the DB with your own subclass of LiveData.

In other words. UI --observes--> YourLiveData --observes--> DBLiveData

P.S. I think genrally speaking you could solve your problem by modifying your DB query, but that is just me assuming you already have "primary contacts" in some other table

Alex.F
  • 5,648
  • 3
  • 39
  • 63