等待插入功能完成(Coroutine)

发布于 2025-02-13 06:09:30 字数 766 浏览 1 评论 0原文

我的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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

入怼 2025-02-20 06:09:32

发布声明刚刚启动了一个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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文