Skip to content

Instantly share code, notes, and snippets.

@hernandazevedo
Created August 28, 2018 17:37
Show Gist options
  • Save hernandazevedo/5596e4561747d5a747d1b7d03bcd8a54 to your computer and use it in GitHub Desktop.
Save hernandazevedo/5596e4561747d5a747d1b7d03bcd8a54 to your computer and use it in GitHub Desktop.
inline fun <reified T : Any> zipLiveData(vararg liveItems: LiveData<*>): LiveData<List<T>> {
return MediatorLiveData<List<T>>().apply {
val zippedObjects = mutableListOf<T>()
liveItems.forEach {
addSource(it, { item ->
zippedObjects.add(item as T)
if (zippedObjects.size == liveItems.size)
value = zippedObjects
})
}
}
}
@hernandazevedozup
Copy link

public static LiveData<List> zipLiveData(LiveData... liveItems){
final List zippedObjects = new ArrayList<>();
final MediatorLiveData<List> mediator = new MediatorLiveData<>();
for(LiveData item: liveItems){
mediator.addSource(item, o -> {
zippedObjects.add(o);
if(zippedObjects.size() == liveItems.length){
mediator.setValue(zippedObjects);
}
});
}
return mediator;
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment