I am retrieving a record from a Room database using Coroutines
because it has to run in a background thread. I want to return the result through the function.
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()
.
.
.
}
However, Android Studio is giving me an error indicator in the return statement return course
that course
must be initialized. How can i successfuly return the value of course
?
-更新:-
我正在尝试获取该记录的值,并将其用于片段中,如下所示:
val course = viewModel.viewModelScope.launch { viewModel.getCourseData() }
textViewName.text = course.Name
textViewInstructor.text = course.instructor
您这样做的方式是错误的。也许您对并发或并发运行的任务有一些误解。
让我清除您的疑虑。
join()
on that to make sure it is done.async
is called on a CoroutineScope while awithContext
is a top level function which expects a CoroutineContext as its parameter.withContext
suspends the caller coroutine till it is completed. While theasync
does not, the return value ofasync
isDeferred<T>
on which when you call.await()
the caller coroutine gets suspended till it the task is completed similar to withContext.因此,您可以通过以下方式完成任务。
选项1:最优化的版本
使函数挂起并与withContext一起使用。它将暂停调用协程直到获取课程。
选项2:使用异步,然后返回Deferred。
更新OP的更新
正如我在评论中所建议的那样,您不能在协程块之外使用暂停的代码块。因为您不能暂停非暂停功能。
进行如下操作: