androidx.paging.LivePagedListBuilder Java Examples

The following examples show how to use androidx.paging.LivePagedListBuilder. 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: QueryRepository.java    From lttrs-android with Apache License 2.0 6 votes vote down vote up
public LiveData<PagedList<ThreadOverviewItem>> getThreadOverviewItems(final EmailQuery query) {
    return Transformations.switchMap(databaseLiveData, new Function<LttrsDatabase, LiveData<PagedList<ThreadOverviewItem>>>() {
        @Override
        public LiveData<PagedList<ThreadOverviewItem>> apply(LttrsDatabase database) {
            return new LivePagedListBuilder<>(database.queryDao().getThreadOverviewItems(query.toQueryString()), 30)
                    .setBoundaryCallback(new PagedList.BoundaryCallback<ThreadOverviewItem>() {
                        @Override
                        public void onZeroItemsLoaded() {
                            Log.d("lttrs", "onZeroItemsLoaded");
                            requestNextPage(query, null); //conceptually in terms of loading indicators this is more of a page request
                            super.onZeroItemsLoaded();
                        }

                        @Override
                        public void onItemAtEndLoaded(@NonNull ThreadOverviewItem itemAtEnd) {
                            Log.d("lttrs", "onItemAtEndLoaded(" + itemAtEnd.emailId + ")");
                            requestNextPage(query, itemAtEnd.emailId);
                            super.onItemAtEndLoaded(itemAtEnd);
                        }
                    })
                    .build();
        }
    });
}
 
Example #2
Source File: MediaFileViewModel.java    From FilePicker with Apache License 2.0 6 votes vote down vote up
private MediaFileViewModel(ContentResolver contentResolver, Configurations configs, Long dirId) {
    this.contentResolver = contentResolver;

    MediaFileDataSource.Factory mediaFileDataSourceFactory = new MediaFileDataSource.Factory(contentResolver, configs, dirId);

    mediaFiles = new LivePagedListBuilder<>(
            mediaFileDataSourceFactory,
            new PagedList.Config.Builder()
                    .setPageSize(Configurations.PAGE_SIZE)
                    .setInitialLoadSizeHint(15)
                    .setMaxSize(Configurations.PAGE_SIZE * 3)
                    .setPrefetchDistance(Configurations.PREFETCH_DISTANCE)
                    .setEnablePlaceholders(false)
                    .build()
    ).build();

    contentResolver.registerContentObserver(mediaFileDataSourceFactory.getUri(), true, contentObserver);
}
 
Example #3
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 #4
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 #5
Source File: CommentViewModel.java    From Infinity-For-Reddit with GNU Affero General Public License v3.0 6 votes vote down vote up
public CommentViewModel(Retrofit retrofit, Locale locale, String accessToken, String username, SortType sortType,
                        boolean areSavedComments) {
    commentDataSourceFactory = new CommentDataSourceFactory(retrofit, locale, accessToken, username, sortType,
            areSavedComments);

    initialLoadingState = Transformations.switchMap(commentDataSourceFactory.getCommentDataSourceLiveData(),
            CommentDataSource::getInitialLoadStateLiveData);
    paginationNetworkState = Transformations.switchMap(commentDataSourceFactory.getCommentDataSourceLiveData(),
            CommentDataSource::getPaginationNetworkStateLiveData);
    hasCommentLiveData = Transformations.switchMap(commentDataSourceFactory.getCommentDataSourceLiveData(),
            CommentDataSource::hasPostLiveData);

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

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

    comments = Transformations.switchMap(sortTypeLiveData, sort -> {
        commentDataSourceFactory.changeSortType(sortTypeLiveData.getValue());
        return (new LivePagedListBuilder(commentDataSourceFactory, pagedListConfig)).build();
    });
}
 
Example #6
Source File: PagedFragment.java    From realm-monarchy with Apache License 2.0 6 votes vote down vote up
@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);
    ButterKnife.bind(this, view);
    pagedDogAdapter = new PagedDogAdapter();
    recyclerView.setHasFixedSize(true);
    recyclerView.setLayoutManager(new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false));
    recyclerView.setAdapter(pagedDogAdapter);
    realmDataSourceFactory = monarchy.createDataSourceFactory(
            realm -> realm.where(RealmDog.class));
    dataSourceFactory = realmDataSourceFactory.map(input -> Dog.create(input.getName()));
    dogs = monarchy.findAllPagedWithChanges(realmDataSourceFactory,
            new LivePagedListBuilder<>(dataSourceFactory, new PagedList.Config.Builder()
                    .setEnablePlaceholders(true)
                    .setPageSize(20)
                    .build())
    );
    dogs.observeForever(observer); // detach != destroy in fragments so this is manual
}
 
Example #7
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 #8
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 #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: ReadOnlyCollectionRepositoryImpl.java    From dhis2-android-sdk with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Handy method to use in conjunction with PagedListAdapter to build paged lists.
 *
 * @param pageSize Length of the page
 * @return A LiveData object of PagedList of elements
 */
@Override
public LiveData<PagedList<M>> getPaged(int pageSize) {
    DataSource.Factory<M, M> factory = new DataSource.Factory<M, M>() {
        @Override
        public DataSource<M, M> create() {
            return getDataSource();
        }
    };

    return new LivePagedListBuilder<>(factory, pageSize).build();
}
 
Example #11
Source File: TrackedEntityInstanceQueryCollectionRepository.java    From dhis2-android-sdk with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
public LiveData<PagedList<TrackedEntityInstance>> getPaged(int pageSize) {
    DataSource.Factory<TrackedEntityInstance, TrackedEntityInstance> factory =
            new DataSource.Factory<TrackedEntityInstance, TrackedEntityInstance>() {
                @Override
                public DataSource<TrackedEntityInstance, TrackedEntityInstance> create() {
                    return getDataSource();
                }
            };

    return new LivePagedListBuilder<>(factory, pageSize).build();
}
 
Example #12
Source File: Monarchy.java    From realm-monarchy with Apache License 2.0 5 votes vote down vote up
/**
 * Returns a LiveData that evaluates the new results on a background looper thread.
 *
 * The resulting list is driven by a PositionalDataSource from the Paging Library.
 *
 * The fetch executor of the provided LivePagedListBuilder will be overridden with Monarchy's own FetchExecutor that Monarchy runs its queries on.
 */
public <R, T extends RealmModel> LiveData<PagedList<R>> findAllPagedWithChanges(DataSource.Factory<Integer, T> dataSourceFactory, LivePagedListBuilder<Integer, R> livePagedListBuilder) {
    assertMainThread();
    final MediatorLiveData<PagedList<R>> mediator = new MediatorLiveData<>();
    if(!(dataSourceFactory instanceof RealmDataSourceFactory)) {
        throw new IllegalArgumentException(
                "The DataSource.Factory provided to this method as the first argument must be the one created by Monarchy.");
    }
    RealmDataSourceFactory<T> realmDataSourceFactory = (RealmDataSourceFactory<T>) dataSourceFactory;
    PagedLiveResults<T> liveResults = realmDataSourceFactory.pagedLiveResults;
    mediator.addSource(liveResults, new Observer<PagedList<T>>() {
        @Override
        public void onChanged(@Nullable PagedList<T> ts) {
            // do nothing, this is to intercept `onActive()` calls to ComputableLiveData
        }
    });
    LiveData<PagedList<R>> computableLiveData = livePagedListBuilder
            .setFetchExecutor(new RealmQueryExecutor(this))
            .build();
    mediator.addSource(computableLiveData, new Observer<PagedList<R>>() {
        @Override
        public void onChanged(@Nullable PagedList<R> data) {
            mediator.postValue(data);
        }
    });
    return mediator;
}
 
Example #13
Source File: TransactionListViewModel.java    From Gander with Apache License 2.0 5 votes vote down vote up
LiveData<PagedList<HttpTransactionUIHelper>> getTransactions(String key) {
    if (key == null || key.trim().length() == 0) {
        return mTransactions;
    } else {
        DataSource.Factory<Integer, HttpTransactionUIHelper> factory = mTransactionDao.getAllTransactionsWith(key, TransactionDao.SearchType.DEFAULT).map(HttpTransactionUIHelper.HTTP_TRANSACTION_UI_HELPER_FUNCTION);
        return new LivePagedListBuilder<>(factory, config).build();
    }
}
 
Example #14
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 #15
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 #16
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 #17
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 #18
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 #19
Source File: ProgramEventDetailRepositoryImpl.java    From dhis2-android-capture-app with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@NonNull
@Override
public LiveData<PagedList<ProgramEventViewModel>> filteredProgramEvents(List<DatePeriod> dateFilter, List<String> orgUnitFilter, List<CategoryOptionCombo> catOptCombList,
                                                                        List<EventStatus> eventStatus, List<State> states, boolean assignedToUser) {
    EventCollectionRepository eventRepo = d2.eventModule().events().byProgramUid().eq(programUid).byDeleted().isFalse();
    if (!dateFilter.isEmpty())
        eventRepo = eventRepo.byEventDate().inDatePeriods(dateFilter);
    if (!orgUnitFilter.isEmpty())
        eventRepo = eventRepo.byOrganisationUnitUid().in(orgUnitFilter);
    if (!catOptCombList.isEmpty())
        eventRepo = eventRepo.byAttributeOptionComboUid().in(UidsHelper.getUids(catOptCombList));
    if (!eventStatus.isEmpty())
        eventRepo = eventRepo.byStatus().in(eventStatus);
    if (!states.isEmpty())
        eventRepo = eventRepo.byState().in(states);
    if (assignedToUser)
        eventRepo = eventRepo.byAssignedUser().eq(getCurrentUser());

    DataSource dataSource = eventRepo.orderByEventDate(RepositoryScope.OrderByDirection.DESC).withTrackedEntityDataValues().getDataSource().map(event -> mapper.eventToProgramEvent(event));

    return new LivePagedListBuilder(new DataSource.Factory() {
        @Override
        public DataSource create() {
            return dataSource;
        }
    }, 20).build();
}
 
Example #20
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 #21
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 #22
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, int filter, boolean nsfw) {
    postDataSourceFactory = new PostDataSourceFactory(retrofit, accessToken, locale, subredditName,
            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 #23
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 #24
Source File: DirViewModel.java    From FilePicker with Apache License 2.0 5 votes vote down vote up
private DirViewModel(ContentResolver contentResolver, Configurations configs) {
    DirDataSource.Factory dirDataSourceFactory = new DirDataSource.Factory(contentResolver, configs);

    dirs = new LivePagedListBuilder<>(
            dirDataSourceFactory,
            new PagedList.Config.Builder()
                    .setPageSize(Configurations.PAGE_SIZE)
                    .setInitialLoadSizeHint(15)
                    .setMaxSize(Configurations.PAGE_SIZE * 3)
                    .setPrefetchDistance(Configurations.PREFETCH_DISTANCE)
                    .setEnablePlaceholders(false)
                    .build()
    ).build();
}
 
Example #25
Source File: PaginationActivity.java    From AdapterDelegates with Apache License 2.0 4 votes vote down vote up
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_pagination);

    RecyclerView recyclerView = findViewById(R.id.recyclerView);
    recyclerView.setLayoutManager(new LinearLayoutManager(this));


    AdapterDelegatesManager<List<DisplayableItem>> delegatesManager =
            new AdapterDelegatesManager<List<DisplayableItem>>()
                    .addDelegate(new AdvertisementAdapterDelegate(this))
                    .addDelegate(new CatAdapterDelegate(this))
                    .addDelegate(new DogAdapterDelegate(this))
                    .addDelegate(new GeckoAdapterDelegate(this))
                    .addDelegate(new SnakeListItemAdapterDelegate(this))
                    .setFallbackDelegate(new LoadingAdapterDelegate(this));


    final PagedListDelegationAdapter<DisplayableItem> adapter =
            new PagedListDelegationAdapter<DisplayableItem>(delegatesManager, callback);

    recyclerView.setAdapter(adapter);


    LiveData<PagedList<DisplayableItem>> pagedListLiveData =
            new LivePagedListBuilder<>(new SampleDataSource.Factory(), 20)
                    .setBoundaryCallback(new PagedList.BoundaryCallback<DisplayableItem>() {
                        @Override
                        public void onZeroItemsLoaded() {
                            Log.d("PaginationSource", "onZeroItemsLoaded");
                            super.onZeroItemsLoaded();
                        }

                        @Override
                        public void onItemAtFrontLoaded(@NonNull DisplayableItem itemAtFront) {
                            Log.d("PaginationSource", "onItemAtFrontLoaded "+itemAtFront);
                            super.onItemAtFrontLoaded(itemAtFront);
                        }

                        @Override
                        public void onItemAtEndLoaded(@NonNull DisplayableItem itemAtEnd) {
                            Log.d("PaginationSource", "onItemAtEndLoaded "+itemAtEnd);
                            super.onItemAtEndLoaded(itemAtEnd);
                        }
                    })
                    .build();

    pagedListLiveData.observe(this, new Observer<PagedList<DisplayableItem>>() {
        @Override
        public void onChanged(PagedList<DisplayableItem> displayableItems) {
            adapter.submitList(displayableItems);
        }
    });

}
 
Example #26
Source File: TransactionListViewModel.java    From Gander with Apache License 2.0 4 votes vote down vote up
public TransactionListViewModel(Application application) {
    super(application);
    mTransactionDao = Gander.getGanderStorage().getTransactionDao();
    DataSource.Factory<Integer, HttpTransactionUIHelper> factory = mTransactionDao.getAllTransactions().map(HttpTransactionUIHelper.HTTP_TRANSACTION_UI_HELPER_FUNCTION);
    mTransactions = new LivePagedListBuilder<>(factory, config).build();
}
 
Example #27
Source File: SearchRepositoryImpl.java    From dhis2-android-capture-app with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
@NonNull
@Override
public LiveData<PagedList<SearchTeiModel>> searchTrackedEntities(@Nullable Program selectedProgram,
                                                                 @NonNull String trackedEntityType,
                                                                 @NonNull List<String> orgUnits,
                                                                 @Nonnull List<State> states,
                                                                 @NonNull List<EventStatus> eventStatuses,
                                                                 @Nullable HashMap<String, String> queryData,
                                                                 boolean assignedToMe,
                                                                 boolean isOnline) {

    TrackedEntityInstanceQueryCollectionRepository trackedEntityInstanceQuery =
            getFilteredRepository(selectedProgram,
                    trackedEntityType,
                    orgUnits,
                    states,
                    queryData,
                    assignedToMe);

    DataSource<TrackedEntityInstance, SearchTeiModel> dataSource;

    if (isOnline && states.isEmpty()) {
        dataSource = trackedEntityInstanceQuery.offlineFirst().getDataSource()
                .mapByPage(list -> filterByStatus(list, eventStatuses))
                .mapByPage(this::filterDeleted)
                .mapByPage(list -> TrackedEntityInstanceExtensionsKt.filterDeletedEnrollment(list, d2, selectedProgram != null ? selectedProgram.uid() : null))
                .map(tei -> transform(tei, selectedProgram, false));
    } else {
        dataSource = trackedEntityInstanceQuery.offlineOnly().getDataSource()
                .mapByPage(list -> filterByStatus(list, eventStatuses))
                .mapByPage(this::filterDeleted)
                .mapByPage(list -> TrackedEntityInstanceExtensionsKt.filterDeletedEnrollment(list, d2, selectedProgram != null ? selectedProgram.uid() : null))
                .map(tei -> transform(tei, selectedProgram, true));
    }

    return new LivePagedListBuilder<>(new DataSource.Factory<TrackedEntityInstance, SearchTeiModel>() {
        @NonNull
        @Override
        public DataSource<TrackedEntityInstance, SearchTeiModel> create() {
            return dataSource;
        }
    }, 10).build();
}
 
Example #28
Source File: ThreadRepository.java    From lttrs-android with Apache License 2.0 4 votes vote down vote up
public LiveData<PagedList<FullEmail>> getEmails(String threadId) {
    return Transformations.switchMap(databaseLiveData, database -> new LivePagedListBuilder<>(database.threadAndEmailDao().getEmails(threadId), 30).build());
}
 
Example #29
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();
}