我正在为一个学校项目学习 Android,我们必须使用 Java,我们不能使用任何外部库。我正在创建一个大学生课程负载跟踪应用程序。目前,我正在开展一项活动,该活动将详细说明Course用户选择的信息。当用户选择 a 时,我需要能够获取多个数据库结果Course:Mentor(Instructor)、a LiveData Listof Assessments 和 a LiveData Listof Notes。我目前有一个Transformations.switchMap设置并正在努力获得Course Mentor. 然而,它似乎LiveData只能有一个这种转换观察者。这是我的代码:
课程详情视图模型
LiveData<Course> currentCourse;
LiveData<Mentor> courseMentor;
LiveData<List<Assessment>> courseAssessments;
LiveData<List<Note>> courseNotes;
final CourseDetailRepository REPO;
public CourseDetailViewModel(@NonNull Application application) {
REPO = new CourseDetailRepository(application);
}
public LiveData<Course> getCurrentCourse(long id) {
if (currentCourse == null) {
currentCourse = REPO.getCourseById(id);
}
// I'm dong the Transformations here because I tried in the Constructor but because currentCourse
// was null, the transformation wasn't kicking off.
// the courseMentor Transformation works, the others don't seem to fire.
courseMentor = Transformations.switchMap(curentCourse, course ->
REPO.getMentorById(course.getMentorId()));
courseAssessments = Transformations.switchMap(currentCourse, course ->
REPO.getAssessmentsByCourse(course.getCourseId()));
courseNotes = Transformations.switchMap(currentCourse, course ->
REPO.getNotesByCourse(course.getCourseId())));
return this.currentCourse;
}
public LiveData<Mentor> getCourseMentor() { return this.courseMentor }
public LiveData<List<Assessment>> getCourseAssessments() { return this.courseAssessments }
public LiveData<List<Note>> getCourseNotes() { return this.courseNotes }
然后我观察这些LiveData对象在我CourseDetailActivity的 UI 中填充:Mentor填充 a 集 a 的选择Spinner,List<Assessment>并List<Note>传递到它们各自RecyclerView Adapter的 s 中。
我有一种感觉,我可以使用类似的东西,MediatorLiveData但是,我真的不完全理解如何正确使用它,即使在网上查看了许多资源之后。我是 Android 新手,这是我的第一个 Android 项目,所以我知道我有很多东西要学,而且我完全愿意接受对设计决策的批评。
非常感谢您的帮助!