Home > database >  Updating incoming list with existing data using operators
Updating incoming list with existing data using operators

Time:01-19

I've 2 lists

  1. Updated list coming from the server.
  2. A locally stored copy of the list that came from the server

The incoming server list data will replace the data in the localList however before doing that I need to merge data from localList into the incomingList because some items in the local list could have been modified.

I'm doing it the following way which looks Java like because of loops. Is there a Kotlin way of doing it?

val localList = List<Animal> ...
fun onIncomingData(incomingList : List<Animal>) {

    val mutableList = incomingList.toMutableList()
    
    mutableList.forEachIndex{ index, freshItem ->
       localList.forEach { localItem ->
          if(localItem is Cat && localItem.id == freshItem.id) {
             mutableList[index] = freshItem.copy(value1 = localItem.value1, value2 = localItem.value2)
            return@forEach
          }
       }
    }
}

CodePudding user response:

Instead of the inner forEach loop, use:

localList.find {it is Cat && it.id == freshItem.id}?.let {
    mutableList[index] = freshItem.copy(value1 = it.value1, value2 = it.value2)
}

Also, I assume your real code will do something with the mutable list you've created.

CodePudding user response:

Instead of replacing elements in a mutable list you could just map over the incoming list and keep some elements while replacing others, like this:

val resultList = incomingList.map{ freshItem ->
    val existing = localList.find { it is Cat && it.id == freshItem.id } as Cat?
    if(existing != null) freshItem.copy(value1 = existing.value1, value2 = existing.value2) else freshItem
}
  •  Tags:  
  • Related