androidx.lifecycle.Transformations Java Examples

The following examples show how to use androidx.lifecycle.Transformations. 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: FlexibleViewModel.java    From FlexibleAdapter with Apache License 2.0 6 votes vote down vote up
public FlexibleViewModel() {
    identifier = new MutableLiveData<>();
    liveItems = Transformations.switchMap(identifier, new Function<Identifier, LiveData<List<AdapterItem>>>() {
        @Override
        public LiveData<List<AdapterItem>> apply(Identifier input) {
            return Transformations.map(getSource(input), new Function<Source, List<AdapterItem>>() {
                @Override
                public List<AdapterItem> apply(Source source) {
                    if (isSourceValid(source)) {
                        return map(source);
                    } else {
                        return liveItems.getValue();
                    }
                }
            });
        }
    });
}
 
Example #2
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 #3
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 #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: 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 #6
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 #7
Source File: AbstractQueryViewModel.java    From lttrs-android with Apache License 2.0 5 votes vote down vote up
AbstractQueryViewModel(@NonNull Application application, ListenableFuture<AccountWithCredentials> account) {
    super(application);

    final WorkManager workManager = WorkManager.getInstance(application);

    this.queryRepository = new QueryRepository(application, account);
    this.important = this.queryRepository.getImportant();
    this.emailModificationWorkInfo = Transformations.map(workManager.getWorkInfosByTagLiveData(AbstractMuaWorker.TAG_EMAIL_MODIFICATION), WorkInfoUtil::allDone);
}
 
Example #8
Source File: AddMembersViewModel.java    From mollyim-android with GNU General Public License v3.0 5 votes vote down vote up
private static LiveData<AddMemberDialogMessageState> getStateWithoutGroupTitle(@NonNull AddMemberDialogMessageStatePartial partialState) {
  if (partialState.recipientId != null) {
    return Transformations.map(Recipient.live(partialState.recipientId).getLiveData(), r -> new AddMemberDialogMessageState(r, ""));
  } else {
    return new DefaultValueLiveData<>(new AddMemberDialogMessageState(partialState.memberCount, ""));
  }
}
 
Example #9
Source File: SetupViewModel.java    From lttrs-android with Apache License 2.0 5 votes vote down vote up
public SetupViewModel(@NonNull Application application) {
    super(application);
    this.mainRepository = new MainRepository(application);
    Transformations.distinctUntilChanged(emailAddress).observeForever(s -> emailAddressError.postValue(null));
    Transformations.distinctUntilChanged(sessionResource).observeForever(s -> sessionResourceError.postValue(null));
    Transformations.distinctUntilChanged(password).observeForever(s -> passwordError.postValue(null));
}
 
Example #10
Source File: SearchQueryViewModel.java    From lttrs-android with Apache License 2.0 5 votes vote down vote up
SearchQueryViewModel(final Application application, final ListenableFuture<AccountWithCredentials> account, final String searchTerm) {
    super(application, account);
    this.searchTerm = searchTerm;
    this.inbox = queryRepository.getInbox();
    this.searchQueryLiveData = Transformations.map(queryRepository.getTrashAndJunk(), trashAndJunk -> EmailQuery.of(
            EmailFilterCondition.builder().text(searchTerm).inMailboxOtherThan(trashAndJunk).build(),
            true
    ));
    init();
}
 
Example #11
Source File: KeywordQueryViewModel.java    From lttrs-android with Apache License 2.0 5 votes vote down vote up
KeywordQueryViewModel(final Application application, ListenableFuture<AccountWithCredentials> account, @NonNull final String keyword) {
    super(application, account);
    this.keyword = keyword;
    //TODO; we probably want to change this to someInThreadHaveKeyword
    this.emailQueryLiveData = Transformations.map(queryRepository.getTrashAndJunk(), trashAndJunk -> EmailQuery.of(
            EmailFilterCondition.builder().hasKeyword(keyword).inMailboxOtherThan(trashAndJunk).build(),
            true
    ));
    init();
}
 
Example #12
Source File: LttrsViewModel.java    From lttrs-android with Apache License 2.0 5 votes vote down vote up
public LttrsViewModel(@NonNull Application application) {
    super(application);
    LOGGER.debug("creating instance of LttrsViewModel");
    this.mainRepository = new MainRepository(application);
    this.account = this.mainRepository.getAccount(null);
    this.threadRepository = new ThreadRepository(application, this.account);
    this.navigatableLabels = Transformations.map(
            this.threadRepository.getMailboxes(),
            LabelUtil::fillUpAndSort
    );
    this.hasAccounts = this.mainRepository.hasAccounts();
}
 
Example #13
Source File: MailboxQueryViewModel.java    From lttrs-android with Apache License 2.0 5 votes vote down vote up
MailboxQueryViewModel(final Application application, ListenableFuture<AccountWithCredentials> account, final String mailboxId) {
    super(application, account);
    this.mailbox = this.queryRepository.getMailboxOverviewItem(mailboxId);
    this.emailQueryLiveData = Transformations.map(mailbox, input -> {
        if (input == null) {
            return EmailQuery.unfiltered(true);
        } else {
            return EmailQuery.of(EmailFilterCondition.builder().inMailbox(input.id).build(), true);
        }
    });
    init();
}
 
Example #14
Source File: CustomNotificationsViewModel.java    From mollyim-android with GNU General Public License v3.0 5 votes vote down vote up
private CustomNotificationsViewModel(@NonNull GroupId groupId, @NonNull CustomNotificationsRepository repository) {
  this.liveGroup              = new LiveGroup(groupId);
  this.repository             = repository;
  this.hasCustomNotifications = Transformations.map(liveGroup.getGroupRecipient(), recipient -> recipient.getNotificationChannel() != null || !NotificationChannels.supported());
  this.isVibrateEnabled       = Transformations.map(liveGroup.getGroupRecipient(), Recipient::getMessageVibrate);
  this.notificationSound      = Transformations.map(liveGroup.getGroupRecipient(), Recipient::getMessageRingtone);

  repository.onLoad(() -> isInitialLoadComplete.postValue(true));
}
 
Example #15
Source File: VideosViewModel.java    From tv-samples with Apache License 2.0 5 votes vote down vote up
@Inject
public VideosViewModel(Application application, VideosRepository repository) {
    super(application);

    mRepository = repository;

    mAllCategories = mRepository.getAllCategories();

    mSearchResults = Transformations.switchMap(
            mQuery, new Function<String, LiveData<List<VideoEntity>>>() {
                @Override
                public LiveData<List<VideoEntity>> apply(final String queryMessage) {
                    return mRepository.getSearchResult(queryMessage);
                }
            });


    mVideoById = Transformations.switchMap(
            mVideoId, new Function<Long, LiveData<VideoEntity>>() {
                @Override
                public LiveData<VideoEntity> apply(final Long videoId) {
                    return mRepository.getVideoById(videoId);
                }
            });

    /**
     * Using switch map function to react to the change of observed variable, the benefits of
     * this mapping method is we don't have to re-create the live data every time.
     */
    mAllVideosByCategory = Transformations.switchMap(mVideoCategory, new Function<String, LiveData<List<VideoEntity>>>() {
        @Override
        public LiveData<List<VideoEntity>> apply(String category) {
            return mRepository.getVideosInSameCategoryLiveData(category);
        }
    });
}
 
Example #16
Source File: LiveGroup.java    From mollyim-android with GNU General Public License v3.0 5 votes vote down vote up
private LiveData<MemberLevel> selfMemberLevel() {
  return Transformations.map(groupRecord, g -> {
    if (g.isAdmin(Recipient.self())) {
      return MemberLevel.ADMIN;
    } else {
      return g.isActive() ? MemberLevel.MEMBER
                          : MemberLevel.NOT_A_MEMBER;
    }
  });
}
 
Example #17
Source File: ReactionsViewModel.java    From mollyim-android with GNU General Public License v3.0 5 votes vote down vote up
public @NonNull LiveData<List<EmojiCount>> getEmojiCounts() {
  return Transformations.map(repository.getReactions(),
                             reactionList -> Stream.of(reactionList)
                                                   .groupBy(Reaction::getEmoji)
                                                   .sorted(this::compareReactions)
                                                   .map(entry -> new EmojiCount(entry.getKey(), entry.getValue().size()))
                                                   .toList());
}
 
Example #18
Source File: ReactionsViewModel.java    From mollyim-android with GNU General Public License v3.0 5 votes vote down vote up
public @NonNull LiveData<List<Reaction>> getRecipients() {
  return Transformations.switchMap(filterEmoji,
                                   emoji -> Transformations.map(repository.getReactions(),
                                                                reactions -> Stream.of(reactions)
                                                                                   .filter(reaction -> emoji == null || reaction.getEmoji().equals(emoji))
                                                                                   .toList()));
}
 
Example #19
Source File: LiveGroup.java    From mollyim-android with GNU General Public License v3.0 5 votes vote down vote up
public LiveGroup(@NonNull GroupId groupId) {
  Context                        context       = ApplicationDependencies.getApplication();
  MutableLiveData<LiveRecipient> liveRecipient = new MutableLiveData<>();

  this.groupDatabase = DatabaseFactory.getGroupDatabase(context);
  this.recipient     = Transformations.switchMap(liveRecipient, LiveRecipient::getLiveData);
  this.groupRecord   = LiveDataUtil.filterNotNull(LiveDataUtil.mapAsync(recipient, groupRecipient-> groupDatabase.getGroup(groupRecipient.getId()).orNull()));

  SignalExecutors.BOUNDED.execute(() -> liveRecipient.postValue(Recipient.externalGroup(context, groupId).live()));
}
 
Example #20
Source File: ManageGroupViewModel.java    From mollyim-android with GNU General Public License v3.0 5 votes vote down vote up
private ManageGroupViewModel(@NonNull Context context, @NonNull ManageGroupRepository manageGroupRepository) {
  this.context               = context;
  this.manageGroupRepository = manageGroupRepository;

  manageGroupRepository.getGroupState(this::groupStateLoaded);

  LiveGroup liveGroup = new LiveGroup(manageGroupRepository.getGroupId());

  this.title                     = Transformations.map(liveGroup.getTitle(),
                                                       title -> TextUtils.isEmpty(title) ? context.getString(R.string.Recipient_unknown)
                                                                                         : title);
  this.isAdmin                   = liveGroup.isSelfAdmin();
  this.canCollapseMemberList     = LiveDataUtil.combineLatest(memberListCollapseState,
                                                              Transformations.map(liveGroup.getFullMembers(), m -> m.size() > MAX_COLLAPSED_MEMBERS),
                                                              (state, hasEnoughMembers) -> state != CollapseState.OPEN && hasEnoughMembers);
  this.members                   = LiveDataUtil.combineLatest(liveGroup.getFullMembers(),
                                                              memberListCollapseState,
                                                              this::filterMemberList);
  this.pendingMemberCount        = liveGroup.getPendingMemberCount();
  this.memberCountSummary        = liveGroup.getMembershipCountDescription(context.getResources());
  this.fullMemberCountSummary    = liveGroup.getFullMembershipCountDescription(context.getResources());
  this.editMembershipRights      = liveGroup.getMembershipAdditionAccessControl();
  this.editGroupAttributesRights = liveGroup.getAttributesAccessControl();
  this.disappearingMessageTimer  = Transformations.map(liveGroup.getExpireMessages(), expiration -> ExpirationUtil.getExpirationDisplayValue(context, expiration));
  this.canEditGroupAttributes    = liveGroup.selfCanEditGroupAttributes();
  this.canAddMembers             = liveGroup.selfCanAddMembers();
  this.groupRecipient            = liveGroup.getGroupRecipient();
  this.muteState                 = Transformations.map(this.groupRecipient,
                                                       recipient -> new MuteState(recipient.getMuteUntil(), recipient.isMuted()));
  this.hasCustomNotifications    = Transformations.map(this.groupRecipient,
                                                       recipient -> recipient.getNotificationChannel() != null || !NotificationChannels.supported());
  this.canLeaveGroup             = liveGroup.isActive();
  this.canBlockGroup             = Transformations.map(this.groupRecipient, recipient -> !recipient.isBlocked());
}
 
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, 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 #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, 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 #24
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 #25
Source File: AddMembersViewModel.java    From mollyim-android with GNU General Public License v3.0 5 votes vote down vote up
private AddMembersViewModel(@NonNull GroupId groupId) {
  repository           = new AddMembersRepository();
  partialState         = new MutableLiveData<>();
  addMemberDialogState = LiveDataUtil.combineLatest(Transformations.map(new LiveGroup(groupId).getTitle(), AddMembersViewModel::titleOrDefault),
                                                    Transformations.switchMap(partialState, AddMembersViewModel::getStateWithoutGroupTitle),
                                                    AddMembersViewModel::getStateWithGroupTitle);
}
 
Example #26
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 #27
Source File: ManageNotificationsViewModel.java    From zephyr with MIT License 5 votes vote down vote up
public ManageNotificationsViewModel(Application application) {
    super(application);

    mSearchQuery = new MutableLiveData<>();
    mSearchQuery.setValue(null);

    mObservableNotificationPreferences = Transformations.switchMap(mSearchQuery, input -> {
        if (StringUtils.isNullOrEmpty(input)) {
            return mDataRepository.getNotificationPreferences();
        } else {
            return mDataRepository.getNotificationPreferencesByName(input);
        }
    });
}
 
Example #28
Source File: AddGroupDetailsViewModel.java    From mollyim-android with GNU General Public License v3.0 5 votes vote down vote up
private AddGroupDetailsViewModel(@NonNull RecipientId[] recipientIds,
                                 @NonNull AddGroupDetailsRepository repository)
{
  this.repository = repository;

  MutableLiveData<List<GroupMemberEntry.NewGroupCandidate>> initialMembers = new MutableLiveData<>();

  LiveData<Boolean> isValidName = Transformations.map(name, name -> !TextUtils.isEmpty(name));
  members       = LiveDataUtil.combineLatest(initialMembers, deleted, AddGroupDetailsViewModel::filterDeletedMembers);
  isMms         = Transformations.map(members, this::isAnyForcedSms);
  canSubmitForm = LiveDataUtil.combineLatest(isMms, isValidName, (mms, validName) -> mms || validName);

  repository.resolveMembers(recipientIds, initialMembers::postValue);
}
 
Example #29
Source File: QueryRepository.java    From lttrs-android with Apache License 2.0 5 votes vote down vote up
public LiveData<MailboxOverviewItem> getMailboxOverviewItem(final String mailboxId) {
    if (mailboxId == null) {
        return Transformations.switchMap(databaseLiveData, database -> database.mailboxDao().getMailboxOverviewItemLiveData(Role.INBOX));
    } else {
        return Transformations.switchMap(databaseLiveData, database -> database.mailboxDao().getMailboxOverviewItemLiveData(mailboxId));
    }
}
 
Example #30
Source File: ConversationGroupViewModel.java    From mollyim-android with GNU General Public License v3.0 4 votes vote down vote up
private ConversationGroupViewModel() {
  liveRecipient                     = new MutableLiveData<>();
  LiveData<GroupRecord> groupRecord = LiveDataUtil.mapAsync(liveRecipient, this::getGroupRecordForRecipient);
  groupActiveState                  = Transformations.distinctUntilChanged(Transformations.map(groupRecord, this::mapToGroupActiveState));
}