简体   繁体   English

等待插入函数完成(协程)

[英]Wait for insert function to complete (Coroutine)

I have the following function in my ViewModel:我的 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. movieId 始终为 0。上面我有两个日志, launch{}中的一个显示正确的 id,但另一个显示 0。我不知道如何强制我的活动中的代码等到方法完成。

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() .协程内部发生的事情与函数的其余部分无关,这就是为什么启动语句之后的代码会在启动后立即执行,并且可能会在您的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.正如 broot 已经提到的,您可以使视图模型的整个insertMovie()函数暂停并从您的活动/片段启动协程。

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.另一种方法是在您的协程完成时更新某种流或 liveData 并让您的视图对此做出反应。 Here is a link to the documentation for StateFlow and SharedFlow: https://developer.android.com/kotlin/flow/stateflow-and-sharedflow这是 StateFlow 和 SharedFlow 文档的链接: https ://developer.android.com/kotlin/flow/stateflow-and-sharedflow

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM