https://kotlinlang.org logo
#android
Title
# android
r

Remy Benza

04/05/2020, 3:05 PM
Quick question, I got two lists. List A are local photos (Android room database), List B are photos from the network. I want to compare both lists and show a 'favorite' icon if an item from List A is present in List B
b

bezrukov

04/05/2020, 4:16 PM
create a set with local photo's ids:
val localIds = localPhotos.map { it.id }.toSet()
then just use map on listB
listB.map { it.copy(isFavorite = localIds.contains(it.id)) }
Most likely there is no simplier (with the ~same performance) way to do this
r

Remy Benza

04/06/2020, 3:49 PM
Thnx, will try this approach. To complicate my case a little more, it needs to be reactive. So when a user removes an photo from the local database, this needs to be shown in List B immediately. Both are LiveData lists.
I was looking at .map and .switchMap operators for LiveData but not sure which one would suit my case
b

bezrukov

04/06/2020, 4:54 PM
You need something like Rx's combineLatest, in LiveData you need to use MediatorLiveData - implementation will be like this - https://gist.github.com/y-polek/42afe8fdb1518db471fb27e646526a06#file-livedataext-kt-L20
r

Remy Benza

04/07/2020, 6:17 AM
thanks, but I am using coroutines. I will try to return a Flow from my room Dao and in my repository write the logic you provide above.
b

bezrukov

04/07/2020, 6:41 AM
r

Remy Benza

04/07/2020, 6:57 PM
LiveData in viewmodels for views to observe, suspending functions in repository and room db. Thnx for the link