使用GithubBrowserSample在viewmodel中进行存储库方法调用而无需transform.switchmap

时间:2019-05-17 13:47:04

标签: android mvvm dagger-2 android-architecture-components android-livedata

Google的GithubBrowserSample取决于是否进行搜索,以便它调用结果。在我的方案中,没有任何搜索,我只想在片段加载时调用它。但是,我不确定如何执行此操作。利用断点和反复试验,我似乎无法将其标记为进入我选择的存储库方法。任何提示将不胜感激。

我的代码的一些摘要:

public class CategoryViewModel extends ViewModel {

    private final LiveData<Resource<List<Category>>> categories;

    @Inject
    CategoryViewModel(@NonNull CategoryRepository categoryRepository){
        categories = categoryRepository.getDBCategories();
    }

与样本中的等效:

public class SearchViewModel extends ViewModel {

    private final MutableLiveData<String> query = new MutableLiveData<>();

    private final LiveData<Resource<List<Repo>>> results;

    private final NextPageHandler nextPageHandler;

    @Inject
    SearchViewModel(RepoRepository repoRepository) {
        nextPageHandler = new NextPageHandler(repoRepository);
        results = Transformations.switchMap(query, search -> {
            if (search == null || search.trim().length() == 0) {
                return AbsentLiveData.create();
            } else {
                return repoRepository.search(search);
            }
        });
    }

1 个答案:

答案 0 :(得分:0)

对于同一条船上的其他任何人,只需修改SearchViewModel构造函数以对查询进行硬编码,我很快就能弄清楚,即使在搜索片段上观察到数据时,它也可以立即加载到示例应用程序上

所以我打开了SearchViewModel:

@Inject
SearchViewModel(RepoRepository repoRepository) {
    nextPageHandler = new NextPageHandler(repoRepository);
    results = Transformations.switchMap(query, search -> {
        if (search == null || search.trim().length() == 0) {
           return AbsentLiveData.create();
        } else {
            return repoRepository.search(search);
        }
    });
}

收件人

@Inject
SearchViewModel(RepoRepository repoRepository) {
    results = repoRepository.search("shadow");
    nextPageHandler = new NextPageHandler(repoRepository);
}

希望这对其他人有帮助。