繁体   English   中英

使用协同程序更新UI异步调用

[英]Update UI async call with coroutines

我必须通过对房间数据库的异步调用来更新UI,但是当我这样做时,我遇到了这个错误:android.view.ViewRootImpl $ CalledFromWrongThreadException:只有创建视图层次结构的原始线程才能触及其视图。

// FavoritesPresenter.kt

GlobalScope.launch {
    favoritesView.showFavorites(ProductProvider.getAllProducts() as ArrayList<Product>)
}

// ProductProvider.kt

fun getAllProducts() : MutableList<Product> {
    return dao.getAllProducts()
}

// ProductDao.kt

@Query("SELECT * FROM product")
fun getAllProducts(): MutableList<Product>

我需要的是通过我的ProductProvider更新我的UI,因为我将用于所有我需要可靠解决方案的实体。

2.1室 (目前处于alpha版)增加了对Kotlin协程的支持。 您可以执行以下操作:

  1. ProductDaoProductProvider函数标记为暂停

     // ProductDao.kt @Query("SELECT * FROM product") suspend fun getAllProducts(): List<Product> // ProductProvider.kt suspend fun getAllProducts(): List<Product> = dao.getAllProducts() 
  2. FavoritesPresenter为协程创建本地范围:

     class FavoritesPresenter { private var favoritesView: FavoritesView? = null private val provider: ProductProvider = ...// initialize it somehow private var job: Job = Job() private val scope = CoroutineScope(job + Dispatchers.Main) fun getProducts() { scope.launch { favoritesView?.showFavorites(provider.getAllProducts()) } } fun attachView(view: FavoritesView) { this.favoritesView = view } fun detachView() { job.cancel() // cancel the job when Activity or Fragment is destroyed favoritesView = null } interface FavoritesView { fun showFavorites(products: List<Product>) } } 
  3. ActivityFragment使用FavoritesPresenter

     class MainActivity : AppCompatActivity(), FavoritesPresenter.FavoritesView { lateinit var presenter: FavoritesPresenter override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) // ... presenter = FavoritesPresenter() presenter.attachView(this) presenter.getProducts() } override fun onDestroy() { presenter.detachView() super.onDestroy() } override fun showFavorites(products: List<Product>) { // use products to update UI } } 

要使用Dispatchers.Main导入:

implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-android:1.1.1'

您应该使用IO协程从Room中取出,并切换到Main(UI)协程以更新视图。

尝试:

GlobalScope.launch(Dispatchers.IO) {
            val products = ProductProvider.getAllProducts() as ArrayList<Product>
            withContext(Dispatchers.Main) {
                favoritesView.showFavorites(products)
            }
        }

确保安装了Android Coroutine库,以便Main Dispatcher正确识别Android主线程。

api "org.jetbrains.kotlinx:kotlinx-coroutines-android:1.1.1"

最好不要使用GlobalScope,而是使用自己的CoroutineContext,例如:

class YourActivity : CoroutineScope {
    private lateinit var job: Job

    // context for io thread
    override val coroutineContext: CoroutineContext
        get() = Dispatchers.IO + job

    override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)

    job = Job()
  }

    fun toDoSmth() {
        launch {
            // task, do smth in io thread
            withContext(Dispatchers.Main) {
              // do smth in main thread after task is finished
            }                  
        }
    }

   override fun onDestroy() {
      job.cancel()
      super.onDestroy()
   }
}

暂无
暂无

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

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