等待插入功能完成(Coroutine)
我的ViewModel中有以下功能:
fun insertMovie(movie: Movie): Long {
var movieId = 0L
viewModelScope.launch {
movieId = repository.insertMovie(movie)
Log.i(LOG_TAG, "add movie with id $movieId within launch")
}
Log.i(LOG_TAG, "add movieId with id $movieId")
return movieId
}
然后在DAO中的以下功能:
@Suppress("RedundantSuspendModifier")
@WorkerThread
suspend fun insertMovie(movie: Movie): Long {
return movieDao.insert(movie)
}
在我的活动中,我正在执行以下操作:
viewModel.viewModelScope.launch {
val movieId = viewModel.insertMovie(Movie(...))
MovieID始终为0。在上方,我有两个日志,abound> laight {} 显示正确的ID,但另一个显示为0。我不知道如何强制活动中的代码等待直到方法完成。
I have the following function in my ViewModel:
fun insertMovie(movie: Movie): Long {
var movieId = 0L
viewModelScope.launch {
movieId = repository.insertMovie(movie)
Log.i(LOG_TAG, "add movie with id $movieId within launch")
}
Log.i(LOG_TAG, "add movieId with id $movieId")
return movieId
}
Then the following in the Dao:
@Suppress("RedundantSuspendModifier")
@WorkerThread
suspend fun insertMovie(movie: Movie): Long {
return movieDao.insert(movie)
}
In my activity I am doing the following:
viewModel.viewModelScope.launch {
val movieId = viewModel.insertMovie(Movie(...))
The movieId is always 0. Above I have two logs, the one within the launch{}
shows the right id, but the other shows 0. I don't know how to force the code in my activity to wait until the method completes.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
发布声明刚刚启动了一个Coroutine。 Coroutine内部发生的事情对函数的其余部分无关紧要,这就是为什么启动语句后的代码在启动后立即获得执行,并且可能会在您的
repository.intertmovie()
之前完成。正如布罗特已经提到的那样,您可以使视图模型的悬挂的整个
insertMovie()
函数从您的活动/片段中启动coroutine。另一种方法是让某种流程或寿命在完成Coroutine后会更新,并让您的视图对此做出反应。这是指向状态流和共享流的文档的链接: https:// developer。 android.com/kotlin/flow/stateflow-and-sharedflow
A launch statement just launches a coroutine. What happens inside the coroutine does not matter to the rest of the function, thats why the code after the launch statement gets executet immediately after the launch and will probably be done before your
repository.insertMovie()
.As broot already mentioned, you could make the whole
insertMovie()
function of your viewmodel suspend and launch a coroutine from your activity/fragment.Another way would be to have some kind of flow or liveData that gets updated when your coroutine is done and let your view react to that. Here is a link to the documentation for StateFlow and SharedFlow: https://developer.android.com/kotlin/flow/stateflow-and-sharedflow