简体   繁体   English

如何等待协程 Dispatch.IO 数据库查询完成以填充 RecyclerView

[英]How to wait for coroutine Dispatch.IO database query to finish to populate RecyclerView

I'm rewriting my Java note taking app in Kotlin.我正在用 Kotlin 重写我的 Java 笔记应用程序。 I'm trying to populate a RecyclerView with TextViews built from my SQLite database query, but I can't figure out how to make it wait for the query to be done, or take an action when it is done.我正在尝试使用从我的 SQLite 数据库查询构建的 TextView 填充 RecyclerView,但我无法弄清楚如何让它等待查询完成,或者在完成时采取行动。

In my Java version I accomplished this by using AsyncTask for the query and then calling PostExecute.在我的 Java 版本中,我通过使用 AsyncTask 进行查询然后调用 PostExecute 来完成此操作。

Now in my Kotlin version I'm using launch(Dispatchers.IO), but I'm not sure how to do the rest.现在,在我的 Kotlin 版本中,我正在使用 launch(Dispatchers.IO),但我不确定如何进行其余操作。 How do I accomplish the same functionality?我如何实现相同的功能?

In coroutines you can make a queue of non-identical coroutine codes.在协程中,您可以创建一个由不同协程代码组成的队列。 For example one block from coroutine1 and another one from coroutine2 and make them run sequentially.例如,coroutine1 中的一个块和 coroutine2 中的另一个块,并使它们按顺序运行。 It is possible using withContext(CoroutineContext)可以使用withContext(CoroutineContext)

Assume this code:假设这段代码:

fun uiCode() {
  // doing things specially on mainThread
}

fun uiCode2() {
  // More work on mainThread
}

fun ioCode() {
  // Doing something not related to mainThread.
}

fun main() {

  launch(Dispatchers.Main) { // 1- run a coroutine
     uiCode() // will run on MainThread
     withContext(Dispachers.IO) { // 2- Coroutine will wait for ioCode
         ioCode() // Will run on ioThread
     }
     uiCode2() // 3- And then it will run this part
  }
}

If you wanted to do it asyncronously, use launch() , instead of withContext() .如果您想异步执行此操作,请使用launch()而不是withContext()

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

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