Java源码示例:android.arch.core.util.Function

示例1
private void subscribeToDbChanges() {
    LiveData<List<LoanWithUserAndBook>> loans
            = mDb.loanModel().findLoansByNameAfter("Mike", getYesterdayDate());

    // Instead of exposing the list of Loans, we can apply a transformation and expose Strings.
    mLoansResult = Transformations.map(loans,
            new Function<List<LoanWithUserAndBook>, String>() {
        @Override
        public String apply(List<LoanWithUserAndBook> loansWithUserAndBook) {
            StringBuilder sb = new StringBuilder();
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm",
                    Locale.US);

            for (LoanWithUserAndBook loan : loansWithUserAndBook) {
                sb.append(String.format("%s\n  (Returned: %s)\n",
                        loan.bookTitle,
                        simpleDateFormat.format(loan.endTime)));
            }
            return sb.toString();
        }
    });
}
 
示例2
private void subscribeToDbChanges() {
    // TODO: Modify this query to show only recent loans from specific user
    LiveData<List<LoanWithUserAndBook>> loans
            = mDb.loanModel().findAllWithUserAndBook();

    // Instead of exposing the list of Loans, we can apply a transformation and expose Strings.
    mLoansResult = Transformations.map(loans,
            new Function<List<LoanWithUserAndBook>, String>() {
        @Override
        public String apply(List<LoanWithUserAndBook> loansWithUserAndBook) {
            StringBuilder sb = new StringBuilder();
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm",
                    Locale.US);

            for (LoanWithUserAndBook loan : loansWithUserAndBook) {
                sb.append(String.format("%s\n  (Returned: %s)\n",
                        loan.bookTitle,
                        simpleDateFormat.format(loan.endTime)));
            }
            return sb.toString();
        }
    });
}
 
示例3
@Override
public LiveData<User> searchUser(String userName){
    return Transformations.map(userDao.getUser(userName), new Function<UserLocal, User>() {
        @Override
        public User apply(UserLocal input) {
            if (input != null) {
                return input.toUser();
            } else {
                return null;
            }
        }
    });
}
 
示例4
public LiveData<Lcee<User>> getUser() {
    if (null == ldUser) {
        ldUsername = new MutableLiveData<>();
        ldUser = Transformations.switchMap(ldUsername, new Function<String, LiveData<Lcee<User>>>() {
            @Override
            public LiveData<Lcee<User>> apply(String username) {
                return userRepository.getUser(username);
            }
        });
    }
    return ldUser;
}
 
示例5
public LiveData<Lcee<Projects>> getProjects() {
    if (null == ldProjects) {
        ldPage = new MutableLiveData<>();
        ldProjects = Transformations.switchMap(ldPage, new Function<Integer, LiveData<Lcee<Projects>>>() {
            @Override
            public LiveData<Lcee<Projects>> apply(Integer page) {
                return projectsRepository.getProjects(page);
            }
        });
    }
    return ldProjects;
}
 
示例6
public LiveData<Lcee<User>> getUser() {
    if (null == ldUser) {
        ldUsername = new MutableLiveData<>();
        ldUser = Transformations.switchMap(ldUsername, new Function<String, LiveData<Lcee<User>>>() {
            @Override
            public LiveData<Lcee<User>> apply(String username) {
                return userRepository.getUser(username);
            }
        });
    }
    return ldUser;
}
 
示例7
public LiveData<Lcee<User>> getUser() {
    if (null == ldUser) {
        ldUsername = new MutableLiveData<>();
        ldUser = Transformations.switchMap(ldUsername, new Function<String, LiveData<Lcee<User>>>() {
            @Override
            public LiveData<Lcee<User>> apply(String username) {
                return userRepository.getUser(username);
            }
        });
    }
    return ldUser;
}
 
示例8
public LiveData<Lcee<User>> getUser() {
    if (null == ldUser) {
        ldUsername = new MutableLiveData<>();
        ldUser = Transformations.switchMap(ldUsername, new Function<String, LiveData<Lcee<User>>>() {
            @Override
            public LiveData<Lcee<User>> apply(String username) {
                return userRepository.getUser(username);
            }
        });
    }
    return ldUser;
}
 
示例9
public LiveData<Lcee<User>> getUser() {
    if (null == ldUser) {
        ldUsername = new MutableLiveData<>();
        ldUser = Transformations.switchMap(ldUsername, new Function<String, LiveData<Lcee<User>>>() {
            @Override
            public LiveData<Lcee<User>> apply(String username) {
                return userRepository.getUser(username);
            }
        });
    }
    return ldUser;
}
 
示例10
@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);
        }
    });
}
 
示例11
/**
 * Applies the given function on the main thread to each value emitted by {@code source}
 * LiveData and returns LiveData, which emits resulting values.
 * <p>
 * The given function {@code func} will be executed on the main thread.
 * <p>
 * Suppose that you have a LiveData, named {@code userLiveData}, that contains user data and you
 * need to display the user name, created by concatenating the first and the last
 * name of the user. You can define a function that handles the name creation, that will be
 * applied to every value emitted by {@code useLiveData}.
 * 
 * <pre>
 * LiveData&lt;User&gt; userLiveData = ...;
 * LiveData&lt;String&gt; userName = Transformations.map(userLiveData, user -&gt; {
 *      return user.firstName + " " + user.lastName
 * });
 * </pre>
 *
 * @param <X>    a type of {@code source} LiveData
 * @param <Y>    a type of resulting LiveData.
 * @param source a {@code LiveData} to listen to
 * @param func   a function to apply
 * @return a LiveData which emits resulting values
 */
@MainThread
public static <X, Y> LiveData<Y> map(@NonNull LiveData<X> source,
        @NonNull final Function<X, Y> func) {
    final MediatorLiveData<Y> result = new MediatorLiveData<>();
    result.addSource(source, new Observer<X>() {
        @Override
        public void onChanged(@Nullable X x) {
            result.setValue(func.apply(x));
        }
    });
    return result;
}
 
示例12
/**
 * Creates a LiveData, let's name it {@code swLiveData}, which follows next flow:
 * it reacts on changes of {@code trigger} LiveData, applies the given function to new value of
 * {@code trigger} LiveData and sets resulting LiveData as a "backing" LiveData
 * to {@code swLiveData}.
 * "Backing" LiveData means, that all events emitted by it will retransmitted
 * by {@code swLiveData}.
 * <p>
 * If the given function returns null, then {@code swLiveData} is not "backed" by any other
 * LiveData.
 * 
 * <p>
 * The given function {@code func} will be executed on the main thread.
 * 
 * <p>
 * Consider the case where you have a LiveData containing a user id. Every time there's a new
 * user id emitted, you want to trigger a request to get the user object corresponding to that
 * id, from a repository that also returns a LiveData.
 * <p>
 * The {@code userIdLiveData} is the trigger and the LiveData returned by the {@code
 * repository.getUserById} is the "backing" LiveData.
 * <p>
 * In a scenario where the repository contains User(1, "Jane") and User(2, "John"), when the
 * userIdLiveData value is set to "1", the {@code switchMap} will call {@code getUser(1)},
 * that will return a LiveData containing the value User(1, "Jane"). So now, the userLiveData
 * will emit User(1, "Jane"). When the user in the repository gets updated to User(1, "Sarah"),
 * the {@code userLiveData} gets automatically notified and will emit User(1, "Sarah").
 * <p>
 * When the {@code setUserId} method is called with userId = "2", the value of the {@code
 * userIdLiveData} changes and automatically triggers a request for getting the user with id
 * "2" from the repository. So, the {@code userLiveData} emits User(2, "John"). The LiveData
 * returned by {@code repository.getUserById(1)} is removed as a source.
 * 
 * <pre>
 * MutableLiveData&lt;String&gt; userIdLiveData = ...;
 * LiveData&lt;User&gt; userLiveData = Transformations.switchMap(userIdLiveData, id -&gt;
 *     repository.getUserById(id));
 * 
 * void setUserId(String userId) {
 *      this.userIdLiveData.setValue(userId);
 * }
 * </pre>
 *
 * @param <X>     a type of {@code source} LiveData
 * @param <Y>     a type of resulting LiveData
 * @param trigger a {@code LiveData} to listen to
 * @param func    a function which creates "backing" LiveData
 * @return the live data
 */
@MainThread
public static <X, Y> LiveData<Y> switchMap(@NonNull LiveData<X> trigger,
        @NonNull final Function<X, LiveData<Y>> func) {
    final MediatorLiveData<Y> result = new MediatorLiveData<>();
    result.addSource(trigger, new Observer<X>() {
        LiveData<Y> mSource;

        @Override
        public void onChanged(@Nullable X x) {
            LiveData<Y> newLiveData = func.apply(x);
            if (mSource == newLiveData) {
                return;
            }
            if (mSource != null) {
                result.removeSource(mSource);
            }
            mSource = newLiveData;
            if (mSource != null) {
                result.addSource(mSource, new Observer<Y>() {
                    @Override
                    public void onChanged(@Nullable Y y) {
                        result.setValue(y);
                    }
                });
            }
        }
    });
    return result;
}
 
示例13
/**
 * Applies the given function on the main thread to each value emitted by {@code source}
 * LiveData and returns LiveData, which emits resulting values.
 * <p>
 * The given function {@code func} will be executed on the main thread.
 * <p>
 * Suppose that you have a LiveData, named {@code userLiveData}, that contains user data and you
 * need to display the user name, created by concatenating the first and the last
 * name of the user. You can define a function that handles the name creation, that will be
 * applied to every value emitted by {@code useLiveData}.
 * 
 * <pre>
 * LiveData&lt;User&gt; userLiveData = ...;
 * LiveData&lt;String&gt; userName = Transformations.map(userLiveData, user -&gt; {
 *      return user.firstName + " " + user.lastName
 * });
 * </pre>
 *
 * @param <X>    a type of {@code source} LiveData
 * @param <Y>    a type of resulting LiveData.
 * @param source a {@code LiveData} to listen to
 * @param func   a function to apply
 * @return a LiveData which emits resulting values
 */
@MainThread
public static <X, Y> LiveData<Y> map(@NonNull LiveData<X> source,
        @NonNull final Function<X, Y> func) {
    final MediatorLiveData<Y> result = new MediatorLiveData<>();
    result.addSource(source, new Observer<X>() {
        @Override
        public void onChanged(@Nullable X x) {
            result.setValue(func.apply(x));
        }
    });
    return result;
}
 
示例14
/**
 * Creates a LiveData, let's name it {@code swLiveData}, which follows next flow:
 * it reacts on changes of {@code trigger} LiveData, applies the given function to new value of
 * {@code trigger} LiveData and sets resulting LiveData as a "backing" LiveData
 * to {@code swLiveData}.
 * "Backing" LiveData means, that all events emitted by it will retransmitted
 * by {@code swLiveData}.
 * <p>
 * If the given function returns null, then {@code swLiveData} is not "backed" by any other
 * LiveData.
 * 
 * <p>
 * The given function {@code func} will be executed on the main thread.
 * 
 * <p>
 * Consider the case where you have a LiveData containing a user id. Every time there's a new
 * user id emitted, you want to trigger a request to get the user object corresponding to that
 * id, from a repository that also returns a LiveData.
 * <p>
 * The {@code userIdLiveData} is the trigger and the LiveData returned by the {@code
 * repository.getUserById} is the "backing" LiveData.
 * <p>
 * In a scenario where the repository contains User(1, "Jane") and User(2, "John"), when the
 * userIdLiveData value is set to "1", the {@code switchMap} will call {@code getUser(1)},
 * that will return a LiveData containing the value User(1, "Jane"). So now, the userLiveData
 * will emit User(1, "Jane"). When the user in the repository gets updated to User(1, "Sarah"),
 * the {@code userLiveData} gets automatically notified and will emit User(1, "Sarah").
 * <p>
 * When the {@code setUserId} method is called with userId = "2", the value of the {@code
 * userIdLiveData} changes and automatically triggers a request for getting the user with id
 * "2" from the repository. So, the {@code userLiveData} emits User(2, "John"). The LiveData
 * returned by {@code repository.getUserById(1)} is removed as a source.
 * 
 * <pre>
 * MutableLiveData&lt;String&gt; userIdLiveData = ...;
 * LiveData&lt;User&gt; userLiveData = Transformations.switchMap(userIdLiveData, id -&gt;
 *     repository.getUserById(id));
 * 
 * void setUserId(String userId) {
 *      this.userIdLiveData.setValue(userId);
 * }
 * </pre>
 *
 * @param <X>     a type of {@code source} LiveData
 * @param <Y>     a type of resulting LiveData
 * @param trigger a {@code LiveData} to listen to
 * @param func    a function which creates "backing" LiveData
 * @return the live data
 */
@MainThread
public static <X, Y> LiveData<Y> switchMap(@NonNull LiveData<X> trigger,
        @NonNull final Function<X, LiveData<Y>> func) {
    final MediatorLiveData<Y> result = new MediatorLiveData<>();
    result.addSource(trigger, new Observer<X>() {
        LiveData<Y> mSource;

        @Override
        public void onChanged(@Nullable X x) {
            LiveData<Y> newLiveData = func.apply(x);
            if (mSource == newLiveData) {
                return;
            }
            if (mSource != null) {
                result.removeSource(mSource);
            }
            mSource = newLiveData;
            if (mSource != null) {
                result.addSource(mSource, new Observer<Y>() {
                    @Override
                    public void onChanged(@Nullable Y y) {
                        result.setValue(y);
                    }
                });
            }
        }
    });
    return result;
}