use of androidx.lifecycle.LiveData in project zype-android by zype.
the class GalleryViewModel method getGalleryRows.
public LiveData<List<GalleryRow>> getGalleryRows(String parentPlaylistId) {
if (data == null) {
this.parentPlaylistId = parentPlaylistId;
data = new MediatorLiveData<>();
liveDataPlaylists = getPlaylists(parentPlaylistId);
liveDataVideos = new HashMap<>();
liveDataNestedPlaylists = new HashMap<>();
data.addSource(liveDataPlaylists, new Observer<List<Playlist>>() {
@Override
public void onChanged(@Nullable List<Playlist> playlists) {
Logger.d("onChanged(): Playlists, size=" + playlists.size());
if (!playlists.isEmpty()) {
data.removeSource(liveDataPlaylists);
}
final List<GalleryRow> galleryRows = new ArrayList<>();
for (final Playlist playlist : playlists) {
final GalleryRow row = new GalleryRow(playlist);
// Add video items to the row if playlist contains any video
if (playlist.playlistItemCount > 0) {
LiveData<List<Video>> playlistVideos = liveDataVideos.get(playlist.id);
if (playlistVideos == null) {
playlistVideos = getPlaylistVideos(playlist.id);
liveDataVideos.put(playlist.id, playlistVideos);
data.addSource(playlistVideos, new Observer<List<Video>>() {
@Override
public void onChanged(@Nullable List<Video> videos) {
Logger.d("onChanged(): Videos (" + playlist.title + "), size=" + videos.size());
row.videos = videos;
if (allDataLoaded(galleryRows)) {
data.setValue(galleryRows);
ZypeApp.needToLoadData = false;
}
}
});
}
} else // Otherwise add nested playlists
{
LiveData<List<Playlist>> nestedPlaylists = liveDataNestedPlaylists.get(playlist.id);
if (nestedPlaylists == null) {
nestedPlaylists = getPlaylists(playlist.id);
liveDataNestedPlaylists.put(playlist.id, nestedPlaylists);
data.addSource(nestedPlaylists, new Observer<List<Playlist>>() {
@Override
public void onChanged(@Nullable List<Playlist> playlists) {
Logger.d("onChanged(): Nested playlists (" + playlist.title + "), size=" + playlists.size());
if (playlists.isEmpty()) {
if (playlistApiRequests.containsKey(playlist.id)) {
if (playlistApiRequests.get(playlist.id)) {
Logger.d("onChanged(): Nested playlists (" + playlist.title + "), wait for API response");
} else {
Logger.d("onChanged(): Nested playlists (" + playlist.title + "), row removed");
galleryRows.remove(row);
}
} else {
Logger.d("onChanged(): Nested playlists (" + playlist.title + "), row removed");
galleryRows.remove(row);
}
} else {
row.nestedPlaylists = playlists;
playlistApiRequests.remove(playlist.id);
}
if (allDataLoaded(galleryRows)) {
data.setValue(galleryRows);
ZypeApp.needToLoadData = false;
}
}
});
}
}
galleryRows.add(row);
}
data.setValue(galleryRows);
}
});
}
return data;
}
Aggregations