public class DataModel { ... public MutableLiveData<List<Repo>> searchRepo(String query) { final MutableLiveData<List<Repo>> repos = new MutableLiveData<>(); githubService.searchRepos(query) .enqueue(new Callback<RepoSearchResponse>() { @Override public void onResponse(@NonNull Call<RepoSearchResponse> call, @NonNull Response<RepoSearchResponse> response) { repos.setValue(response.body().getItems()); } ... }); return repos; } }
public class RepoViewModel extends ViewModel { ... MutableLiveData<List<Repo>> searchRepo(String query) { // NO! return dataModel.searchRepo(query); } }
public class RepoViewModel extends ViewModel { ... private final MutableLiveData<String> query = new MutableLiveData<>(); private final LiveData<List<Repo>> repos; public RepoViewModel(final DataModel dataModel) { ... repos = Transformations.switchMap(query, new Function<String, LiveData<List<Repo>>>() { @Override public LiveData<List<Repo>> apply(String userInput) { return dataModel.searchRepo(userInput); } }); } ... void searchRepo(String userInput) { query.setValue(userInput); } }
/** * A LiveData class that has {@code null} value. */ public class AbsentLiveData extends LiveData { private AbsentLiveData() { postValue(null); } public static <T> LiveData<T> create() { //noinspection unchecked return new AbsentLiveData(); } }
repos = Transformations.switchMap(query, new Function<String, LiveData<List<Repo>>>() { @Override public LiveData<List<Repo>> apply(String userInput) { if (TextUtils.isEmpty(userInput)) { return AbsentLiveData.create(); } else { return dataModel.searchRepo(userInput); } } });
MutableLiveData userIdLiveData = ...; LiveData userLiveData = Transformations.switchMap(userIdLiveData, id -> repository.getUserById(id)); void setUserId(String userId) { this.userIdLiveData.setValue(userId); }
文章来源地址https://www.toymoban.com/news/detail-564692.html
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
LiveData userLiveData = ...; LiveData userName = Transformations.map(userLiveData, user -> { return user.firstName + " " + user.lastName });
文章来源:https://www.toymoban.com/news/detail-564692.html
到了这里,关于Transform LiveData的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!