Java Code Examples for androidx.paging.PagedList#Config

The following examples show how to use androidx.paging.PagedList#Config . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: MessageViewModel.java    From Infinity-For-Reddit with GNU Affero General Public License v3.0 6 votes vote down vote up
public MessageViewModel(Retrofit retrofit, Locale locale, String accessToken, String where) {
    messageDataSourceFactory = new MessageDataSourceFactory(retrofit, locale, accessToken, where);

    initialLoadingState = Transformations.switchMap(messageDataSourceFactory.getMessageDataSourceLiveData(),
            MessageDataSource::getInitialLoadStateLiveData);
    paginationNetworkState = Transformations.switchMap(messageDataSourceFactory.getMessageDataSourceLiveData(),
            MessageDataSource::getPaginationNetworkStateLiveData);
    hasMessageLiveData = Transformations.switchMap(messageDataSourceFactory.getMessageDataSourceLiveData(),
            MessageDataSource::hasPostLiveData);

    whereLiveData = new MutableLiveData<>();
    whereLiveData.postValue(where);

    PagedList.Config pagedListConfig =
            (new PagedList.Config.Builder())
                    .setEnablePlaceholders(false)
                    .setPageSize(25)
                    .build();

    messages = Transformations.switchMap(whereLiveData, newWhere -> {
        messageDataSourceFactory.changeWhere(whereLiveData.getValue());
        return (new LivePagedListBuilder(messageDataSourceFactory, pagedListConfig)).build();
    });
}
 
Example 2
Source File: SubredditListingViewModel.java    From Infinity-For-Reddit with GNU Affero General Public License v3.0 6 votes vote down vote up
public SubredditListingViewModel(Retrofit retrofit, String query, SortType sortType) {
    subredditListingDataSourceFactory = new SubredditListingDataSourceFactory(retrofit, query, sortType);

    initialLoadingState = Transformations.switchMap(subredditListingDataSourceFactory.getSubredditListingDataSourceMutableLiveData(),
            SubredditListingDataSource::getInitialLoadStateLiveData);
    paginationNetworkState = Transformations.switchMap(subredditListingDataSourceFactory.getSubredditListingDataSourceMutableLiveData(),
            SubredditListingDataSource::getPaginationNetworkStateLiveData);
    hasSubredditLiveData = Transformations.switchMap(subredditListingDataSourceFactory.getSubredditListingDataSourceMutableLiveData(),
            SubredditListingDataSource::hasSubredditLiveData);

    sortTypeLiveData = new MutableLiveData<>();
    sortTypeLiveData.postValue(sortType);

    PagedList.Config pagedListConfig =
            (new PagedList.Config.Builder())
                    .setEnablePlaceholders(false)
                    .setPageSize(25)
                    .build();

    subreddits = Transformations.switchMap(sortTypeLiveData, sort -> {
        subredditListingDataSourceFactory.changeSortType(sortTypeLiveData.getValue());
        return new LivePagedListBuilder(subredditListingDataSourceFactory, pagedListConfig).build();
    });
}
 
Example 3
Source File: UserListingViewModel.java    From Infinity-For-Reddit with GNU Affero General Public License v3.0 6 votes vote down vote up
public UserListingViewModel(Retrofit retrofit, String query, SortType sortType) {
    userListingDataSourceFactory = new UserListingDataSourceFactory(retrofit, query, sortType);

    initialLoadingState = Transformations.switchMap(userListingDataSourceFactory.getUserListingDataSourceMutableLiveData(),
            UserListingDataSource::getInitialLoadStateLiveData);
    paginationNetworkState = Transformations.switchMap(userListingDataSourceFactory.getUserListingDataSourceMutableLiveData(),
            UserListingDataSource::getPaginationNetworkStateLiveData);
    hasUserLiveData = Transformations.switchMap(userListingDataSourceFactory.getUserListingDataSourceMutableLiveData(),
            UserListingDataSource::hasUserLiveData);

    sortTypeLiveData = new MutableLiveData<>();
    sortTypeLiveData.postValue(sortType);

    PagedList.Config pagedListConfig =
            (new PagedList.Config.Builder())
                    .setEnablePlaceholders(false)
                    .setPageSize(25)
                    .build();

    users = Transformations.switchMap(sortTypeLiveData, sort -> {
        userListingDataSourceFactory.changeSortType(sortTypeLiveData.getValue());
        return (new LivePagedListBuilder(userListingDataSourceFactory, pagedListConfig)).build();
    });
}
 
Example 4
Source File: MainActivityViewModel.java    From android-popular-movies-app with Apache License 2.0 6 votes vote down vote up
/**
 * Initialize the paged list
 */
private void init(String sortCriteria) {
    Executor executor = Executors.newFixedThreadPool(NUMBER_OF_FIXED_THREADS_FIVE);

    // Create a MovieDataSourceFactory providing DataSource generations
    MovieDataSourceFactory movieDataFactory = new MovieDataSourceFactory(sortCriteria);

    // Configures how a PagedList loads content from the MovieDataSource
    PagedList.Config config = (new PagedList.Config.Builder())
            .setEnablePlaceholders(false)
            // Size hint for initial load of PagedList
            .setInitialLoadSizeHint(INITIAL_LOAD_SIZE_HINT)
            // Size of each page loaded by the PagedList
            .setPageSize(PAGE_SIZE)
            // Prefetch distance which defines how far ahead to load
            .setPrefetchDistance(PREFETCH_DISTANCE)
            .build();

    // The LivePagedListBuilder class is used to get a LiveData object of type PagedList
    mMoviePagedList = new LivePagedListBuilder<>(movieDataFactory, config)
            .setFetchExecutor(executor)
            .build();
}
 
Example 5
Source File: FirestorePagingOptions.java    From FirebaseUI-Android with Apache License 2.0 5 votes vote down vote up
/**
 * Sets the query using {@link Source#DEFAULT} and a custom {@link SnapshotParser}.
 *
 * See {@link #setQuery(Query, Source, PagedList.Config, SnapshotParser)}.
 */
@NonNull
public Builder<T> setQuery(@NonNull Query query,
                           @NonNull PagedList.Config config,
                           @NonNull SnapshotParser<T> parser) {
    return setQuery(query, Source.DEFAULT, config, parser);
}
 
Example 6
Source File: FirestorePagingOptions.java    From FirebaseUI-Android with Apache License 2.0 5 votes vote down vote up
/**
 * Sets the query using {@link Source#DEFAULT} and a {@link ClassSnapshotParser} based
 * on the given Class.
 *
 * See {@link #setQuery(Query, Source, PagedList.Config, SnapshotParser)}.
 */
@NonNull
public Builder<T> setQuery(@NonNull Query query,
                           @NonNull PagedList.Config config,
                           @NonNull Class<T> modelClass) {
    return setQuery(query, Source.DEFAULT, config, modelClass);
}
 
Example 7
Source File: DatabasePagingOptions.java    From FirebaseUI-Android with Apache License 2.0 5 votes vote down vote up
/**
 * Sets the Database query to paginate.
 *
 * @param query the FirebaseDatabase query. This query should only contain orderByKey(), orderByChild() and
 *              orderByValue() clauses. Any limit will cause an error such as limitToLast() or limitToFirst().
 * @param config paging configuration, passed directly to the support paging library.
 * @param parser the {@link SnapshotParser} to parse {@link DataSnapshot} into model
 *               objects.
 * @return this, for chaining.
 */
@NonNull
public Builder<T> setQuery(@NonNull Query query,
                           @NonNull PagedList.Config config,
                           @NotNull SnapshotParser<T> parser) {
    FirebaseDataSource.Factory factory = new FirebaseDataSource.Factory(query);
    mData = new LivePagedListBuilder<>(factory, config).build();

    mParser = parser;
    return this;
}
 
Example 8
Source File: DatabasePagingOptions.java    From FirebaseUI-Android with Apache License 2.0 5 votes vote down vote up
/**
 * Sets the query using a {@link ClassSnapshotParser} based
 * on the given class.
 *
 * See {@link #setQuery(Query, PagedList.Config, SnapshotParser)}.
 */
@NonNull
public Builder<T> setQuery(@NonNull Query query,
                           @NonNull PagedList.Config config,
                           @NonNull Class<T> modelClass) {
    return setQuery(query, config, new ClassSnapshotParser<>(modelClass));
}
 
Example 9
Source File: ObjectBoxDAO.java    From Hentoid with Apache License 2.0 5 votes vote down vote up
private LiveData<PagedList<Content>> getPagedContent(
        int mode,
        String filter,
        List<Attribute> metadata,
        int orderField,
        boolean orderDesc,
        boolean favouritesOnly,
        boolean loadAll) {
    boolean isRandom = (orderField == Preferences.Constant.ORDER_FIELD_RANDOM);

    Query<Content> query;
    if (Mode.SEARCH_CONTENT_MODULAR == mode) {
        query = db.queryContentSearchContent(filter, metadata, favouritesOnly, orderField, orderDesc);
    } else { // Mode.SEARCH_CONTENT_UNIVERSAL
        query = db.queryContentUniversal(filter, favouritesOnly, orderField, orderDesc);
    }

    int nbPages = Preferences.getContentPageQuantity();
    int initialLoad = nbPages * 2;
    if (loadAll) {
        // Trump Android's algorithm by setting a number of pages higher that the actual number of results
        // to avoid having a truncated result set (see issue #501)
        initialLoad = (int) Math.ceil(query.count() * 1.0 / nbPages) * nbPages;
    }

    PagedList.Config cfg = new PagedList.Config.Builder().setEnablePlaceholders(!loadAll).setInitialLoadSizeHint(initialLoad).setPageSize(nbPages).build();

    return new LivePagedListBuilder<>(
            isRandom ? new ObjectBoxRandomDataSource.RandomDataSourceFactory<>(query) : new ObjectBoxDataSource.Factory<>(query),
            cfg
    ).build();
}
 
Example 10
Source File: RoomFileRepository.java    From ArchPackages with GNU General Public License v3.0 5 votes vote down vote up
public RoomFileRepository(Application application) {
    RoomFileDatabase roomFileDatabase = RoomFileDatabase.getRoomFileDatabase(application);
    roomFileDao = roomFileDatabase.roomFileDao();
    listLiveData = roomFileDao.geAlphabetizedFiles();
    PagedList.Config config = new PagedList.Config.Builder()
            .setPageSize(25)
            .setEnablePlaceholders(false)
            .build();
    pagedListLiveData = new LivePagedListBuilder<>(
            roomFileDao.getPagedFiles(), config)
            .setInitialLoadKey(1)
            .build();
}
 
Example 11
Source File: PackagesViewModel.java    From ArchPackages with GNU General Public License v3.0 5 votes vote down vote up
PackagesViewModel(int keywordsParameter,
                  String query,
                  List<String> listRepo,
                  List<String> listArch,
                  String flagged) {
    ResultDataSourceFactory resultDataSourceFactory = new ResultDataSourceFactory(keywordsParameter, query, listRepo, listArch, flagged);
    PagedList.Config pagedListConfig = new PagedList.Config.Builder()
            .setEnablePlaceholders(false)
            .setPageSize(ResultDataSource.PAGE_SIZE)
            .build();
    pagedListLiveData = new LivePagedListBuilder(resultDataSourceFactory, pagedListConfig).build();
}
 
Example 12
Source File: MoviesRemoteDataSource.java    From PopularMovies with MIT License 5 votes vote down vote up
/**
 * Load movies for certain filter.
 */
public RepoMoviesResult loadMoviesFilteredBy(MoviesFilterType sortBy) {
    MovieDataSourceFactory sourceFactory =
            new MovieDataSourceFactory(mMovieService, mExecutors.networkIO(), sortBy);

    // paging configuration
    PagedList.Config config = new PagedList.Config.Builder()
            .setEnablePlaceholders(false)
            .setPageSize(PAGE_SIZE)
            .build();

    // Get the paged list
    LiveData<PagedList<Movie>> moviesPagedList = new LivePagedListBuilder<>(sourceFactory, config)
            .setFetchExecutor(mExecutors.networkIO())
            .build();

    LiveData<Resource> networkState = Transformations.switchMap(sourceFactory.sourceLiveData, new Function<MoviePageKeyedDataSource, LiveData<Resource>>() {
        @Override
        public LiveData<Resource> apply(MoviePageKeyedDataSource input) {
            return input.networkState;
        }
    });

    // Get pagedList and network errors exposed to the viewmodel
    return new RepoMoviesResult(
            moviesPagedList,
            networkState,
            sourceFactory.sourceLiveData
    );
}
 
Example 13
Source File: PostViewModel.java    From Infinity-For-Reddit with GNU Affero General Public License v3.0 5 votes vote down vote up
public PostViewModel(Retrofit retrofit, String accessToken, Locale locale, String subredditName, String query,
                     int postType, SortType sortType, int filter, boolean nsfw) {
    postDataSourceFactory = new PostDataSourceFactory(retrofit, accessToken, locale, subredditName,
            query, postType, sortType, filter, nsfw);

    initialLoadingState = Transformations.switchMap(postDataSourceFactory.getPostDataSourceLiveData(),
            PostDataSource::getInitialLoadStateLiveData);
    paginationNetworkState = Transformations.switchMap(postDataSourceFactory.getPostDataSourceLiveData(),
            PostDataSource::getPaginationNetworkStateLiveData);
    hasPostLiveData = Transformations.switchMap(postDataSourceFactory.getPostDataSourceLiveData(),
            PostDataSource::hasPostLiveData);

    nsfwLiveData = new MutableLiveData<>();
    nsfwLiveData.postValue(nsfw);
    sortTypeLiveData = new MutableLiveData<>();
    sortTypeLiveData.postValue(sortType);

    nsfwAndSortTypeLiveData = new NSFWAndSortTypeLiveData(nsfwLiveData, sortTypeLiveData);

    PagedList.Config pagedListConfig =
            (new PagedList.Config.Builder())
                    .setEnablePlaceholders(false)
                    .setPageSize(25)
                    .build();

    posts = Transformations.switchMap(nsfwAndSortTypeLiveData, nsfwAndSort -> {
        postDataSourceFactory.changeNSFWAndSortType(nsfwLiveData.getValue(), sortTypeLiveData.getValue());
        return (new LivePagedListBuilder(postDataSourceFactory, pagedListConfig)).build();
    });
}
 
Example 14
Source File: PostViewModel.java    From Infinity-For-Reddit with GNU Affero General Public License v3.0 5 votes vote down vote up
public PostViewModel(Retrofit retrofit, String accessToken, Locale locale, String subredditName, int postType,
                     SortType sortType, String where, int filter, boolean nsfw) {
    postDataSourceFactory = new PostDataSourceFactory(retrofit, accessToken, locale, subredditName,
            postType, sortType, where, filter, nsfw);

    initialLoadingState = Transformations.switchMap(postDataSourceFactory.getPostDataSourceLiveData(),
            PostDataSource::getInitialLoadStateLiveData);
    paginationNetworkState = Transformations.switchMap(postDataSourceFactory.getPostDataSourceLiveData(),
            PostDataSource::getPaginationNetworkStateLiveData);
    hasPostLiveData = Transformations.switchMap(postDataSourceFactory.getPostDataSourceLiveData(),
            PostDataSource::hasPostLiveData);

    nsfwLiveData = new MutableLiveData<>();
    nsfwLiveData.postValue(nsfw);
    sortTypeLiveData = new MutableLiveData<>();
    sortTypeLiveData.postValue(sortType);

    nsfwAndSortTypeLiveData = new NSFWAndSortTypeLiveData(nsfwLiveData, sortTypeLiveData);

    PagedList.Config pagedListConfig =
            (new PagedList.Config.Builder())
                    .setEnablePlaceholders(false)
                    .setPageSize(25)
                    .build();

    posts = Transformations.switchMap(nsfwAndSortTypeLiveData, nsfwAndSort -> {
        postDataSourceFactory.changeNSFWAndSortType(nsfwLiveData.getValue(), sortTypeLiveData.getValue());
        return (new LivePagedListBuilder(postDataSourceFactory, pagedListConfig)).build();
    });
}
 
Example 15
Source File: FirestorePagingOptions.java    From FirebaseUI-Android with Apache License 2.0 5 votes vote down vote up
/**
 * Sets the query using a custom {@link Source} and a {@link ClassSnapshotParser} based
 * on the given class.
 *
 * See {@link #setQuery(Query, Source, PagedList.Config, SnapshotParser)}.
 */
@NonNull
public Builder<T> setQuery(@NonNull Query query,
                           @NonNull Source source,
                           @NonNull PagedList.Config config,
                           @NonNull Class<T> modelClass) {
    return setQuery(query, source, config, new ClassSnapshotParser<>(modelClass));
}
 
Example 16
Source File: PostViewModel.java    From Infinity-For-Reddit with GNU Affero General Public License v3.0 5 votes vote down vote up
public PostViewModel(Retrofit retrofit, String accessToken, Locale locale, int postType, SortType sortType,
                     int filter, boolean nsfw) {
    postDataSourceFactory = new PostDataSourceFactory(retrofit, accessToken, locale, postType,
            sortType, filter, nsfw);

    initialLoadingState = Transformations.switchMap(postDataSourceFactory.getPostDataSourceLiveData(),
            PostDataSource::getInitialLoadStateLiveData);
    paginationNetworkState = Transformations.switchMap(postDataSourceFactory.getPostDataSourceLiveData(),
            PostDataSource::getPaginationNetworkStateLiveData);
    hasPostLiveData = Transformations.switchMap(postDataSourceFactory.getPostDataSourceLiveData(),
            PostDataSource::hasPostLiveData);

    nsfwLiveData = new MutableLiveData<>();
    nsfwLiveData.postValue(nsfw);
    sortTypeLiveData = new MutableLiveData<>();
    sortTypeLiveData.postValue(sortType);

    nsfwAndSortTypeLiveData = new NSFWAndSortTypeLiveData(nsfwLiveData, sortTypeLiveData);

    PagedList.Config pagedListConfig =
            (new PagedList.Config.Builder())
                    .setEnablePlaceholders(false)
                    .setPageSize(25)
                    .build();

    posts = Transformations.switchMap(nsfwAndSortTypeLiveData, nsfwAndSort -> {
        postDataSourceFactory.changeNSFWAndSortType(nsfwLiveData.getValue(), sortTypeLiveData.getValue());
        return (new LivePagedListBuilder(postDataSourceFactory, pagedListConfig)).build();
    });
}
 
Example 17
Source File: FirestorePagingOptions.java    From FirebaseUI-Android with Apache License 2.0 5 votes vote down vote up
/**
 * Sets the Firestore query to paginate.
 *
 * @param query the Firestore query. This query should only contain where() and
 *              orderBy() clauses. Any limit() or pagination clauses will cause errors.
 * @param source the data source to use for query data.
 * @param config paging configuration, passed directly to the support paging library.
 * @param parser the {@link SnapshotParser} to parse {@link DocumentSnapshot} into model
 *               objects.
 * @return this, for chaining.
 */
@NonNull
public Builder<T> setQuery(@NonNull Query query,
                           @NonNull Source source,
                           @NonNull PagedList.Config config,
                           @NonNull SnapshotParser<T> parser) {
    // Build paged list
    FirestoreDataSource.Factory factory = new FirestoreDataSource.Factory(query, source);
    mData = new LivePagedListBuilder<>(factory, config).build();

    mParser = parser;
    return this;
}
 
Example 18
Source File: FirestorePagingActivity.java    From FirebaseUI-Android with Apache License 2.0 4 votes vote down vote up
private void setUpAdapter() {
    Query baseQuery = mItemsCollection.orderBy("value", Query.Direction.ASCENDING);

    PagedList.Config config = new PagedList.Config.Builder()
            .setEnablePlaceholders(false)
            .setPrefetchDistance(10)
            .setPageSize(20)
            .build();

    FirestorePagingOptions<Item> options = new FirestorePagingOptions.Builder<Item>()
            .setLifecycleOwner(this)
            .setQuery(baseQuery, config, Item.class)
            .build();

    final FirestorePagingAdapter<Item, ItemViewHolder> adapter =
            new FirestorePagingAdapter<Item, ItemViewHolder>(options) {
                @NonNull
                @Override
                public ItemViewHolder onCreateViewHolder(@NonNull ViewGroup parent,
                                                         int viewType) {
                    View view = LayoutInflater.from(parent.getContext())
                            .inflate(R.layout.item_item, parent, false);
                    return new ItemViewHolder(view);
                }

                @Override
                protected void onBindViewHolder(@NonNull ItemViewHolder holder,
                                                int position,
                                                @NonNull Item model) {
                    holder.bind(model);
                }

                @Override
                protected void onLoadingStateChanged(@NonNull LoadingState state) {
                    switch (state) {
                        case LOADING_INITIAL:
                        case LOADING_MORE:
                            mSwipeRefreshLayout.setRefreshing(true);
                            break;
                        case LOADED:
                            mSwipeRefreshLayout.setRefreshing(false);
                            break;
                        case FINISHED:
                            mSwipeRefreshLayout.setRefreshing(false);
                            showToast("Reached end of data set.");
                            break;
                        case ERROR:
                            showToast("An error occurred.");
                            retry();
                            break;
                    }
                }

                @Override
                protected void onError(@NonNull Exception e) {
                    mSwipeRefreshLayout.setRefreshing(false);
                    Log.e(TAG, e.getMessage(), e);
                }
            };

    mRecycler.setLayoutManager(new LinearLayoutManager(this));
    mRecycler.setAdapter(adapter);

    mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
        @Override
        public void onRefresh() {
            adapter.refresh();
        }
    });
}
 
Example 19
Source File: FirebaseDbPagingActivity.java    From FirebaseUI-Android with Apache License 2.0 4 votes vote down vote up
private void setUpAdapter() {

        //Initialize Paging Configurations
        PagedList.Config config = new PagedList.Config.Builder()
                .setEnablePlaceholders(false)
                .setPrefetchDistance(5)
                .setPageSize(30)
                .build();

        //Initialize Firebase Paging Options
        DatabasePagingOptions<Item> options = new DatabasePagingOptions.Builder<Item>()
                .setLifecycleOwner(this)
                .setQuery(mQuery, config, Item.class)
                .build();

        //Initializing Adapter
        final FirebaseRecyclerPagingAdapter<Item, ItemViewHolder> mAdapter =
                new FirebaseRecyclerPagingAdapter<Item, ItemViewHolder>(options) {
                    @NonNull
                    @Override
                    public ItemViewHolder onCreateViewHolder(@NonNull ViewGroup parent,
                                                             int viewType) {
                        View view = LayoutInflater.from(parent.getContext())
                                .inflate(R.layout.item_item, parent, false);
                        return new ItemViewHolder(view);
                    }

                    @Override
                    protected void onBindViewHolder(@NonNull ItemViewHolder holder,
                                                    int position,
                                                    @NonNull Item model) {
                        holder.bind(model);
                    }

                    @Override
                    protected void onLoadingStateChanged(@NonNull LoadingState state) {
                        switch (state) {
                            case LOADING_INITIAL:
                            case LOADING_MORE:
                                mSwipeRefreshLayout.setRefreshing(true);
                                break;
                            case LOADED:
                                mSwipeRefreshLayout.setRefreshing(false);
                                break;
                            case FINISHED:
                                mSwipeRefreshLayout.setRefreshing(false);
                                showToast(getString(R.string.paging_finished_message));
                                break;
                            case ERROR:
                                showToast(getString(R.string.unknown_error));
                                break;
                        }
                    }

                    @Override
                    protected void onError(DatabaseError databaseError) {
                        mSwipeRefreshLayout.setRefreshing(false);
                        Log.e(TAG, databaseError.getDetails(), databaseError.toException());
                    }
                };

        mRecycler.setLayoutManager(new LinearLayoutManager(this));
        mRecycler.setAdapter(mAdapter);

        // Reload data on swipe
        mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                //Reload Data
                mAdapter.refresh();
            }
        });
    }
 
Example 20
Source File: ObjectBoxDAO.java    From Hentoid with Apache License 2.0 3 votes vote down vote up
public LiveData<PagedList<Content>> getErrorContent() {
    Query<Content> query = db.selectErrorContentQ();

    PagedList.Config cfg = new PagedList.Config.Builder().setEnablePlaceholders(true).setInitialLoadSizeHint(40).setPageSize(20).build();

    return new LivePagedListBuilder<>(new ObjectBoxDataSource.Factory<>(query), cfg).build();
}