【发布时间】:2020-05-09 13:29:57
【问题描述】:
我正在使用 Coroutines 从 Room 数据库中检索记录,因为它必须在后台线程中运行。我想通过函数返回结果。
class LessonRepository(val app: Application) {
private val courseDao = MyDatabase.getDatabase(app).courseDao()
}
fun getCourseData(): Course {
var course: Course
CoroutineScope(Dispatchers.IO).launch {
course = courseDao.getCourse(globalSelectedCourse)
}
return course
}
视图模型
class LessonViewModel(app: Application): AndroidViewModel(app) {
private val lessonDataRepository = LessonRepository(app)
val lessonData = lessonDataRepository.lessonData
val selectedLesson = MutableLiveData<Lesson>()
fun getCourseData() : Course {
return lessonDataRepository.getCourseData()
}
}
我想在我的片段中使用返回值:
class DetailFragment : Fragment(), LessonRecyclerAdapter.LessonItemListener {
.
.
.
viewModel = ViewModelProvider(this).get(LessonViewModel::class.java)
val course = viewModel.getCourseData()
.
.
.
}
但是,Android Studio 在返回语句 return course 中给了我一个错误指示符,表明必须初始化 course。我怎样才能成功返回course的值?
-- 更新:--
我正在尝试获取该记录的值并在我的片段中使用它,如下所示:
val course = viewModel.viewModelScope.launch { viewModel.getCourseData() }
textViewName.text = course.Name
textViewInstructor.text = course.instructor
【问题讨论】:
标签: android kotlin android-room kotlin-coroutines