如何在主线程上使用协程GlobalScope? [英] How to use coroutines GlobalScope on the main thread?

查看:969
本文介绍了如何在主线程上使用协程GlobalScope?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在0.30.0中使用最新的协程,并且在弄清楚如何使用新范围时遇到了麻烦.在原始的协程中,我可以使用UI或CommonPool设置上下文,并且一切正常.

I'm trying to use the latest coroutines in 0.30.0, and having trouble figuring out how to use the new scoping. In the original coroutines I could set the context with UI or CommonPool and everything worked correctly.

现在,我正在尝试从房间数据库中读取数据时在ViewModel中使用GlobalScope,然后我想将返回的值分配给LiveData对象.

Now I'm trying to use the GlobalScope in my ViewModel while reading from a room database, and then I want to assign the value returned to my LiveData object.

尝试设置LiveData值时出现以下错误

I'm getting the following error when I try to set the LiveData value

java.lang.IllegalStateException:无法在 后台线程

java.lang.IllegalStateException: Cannot invoke setValue on a background thread

fun getContact() {
        GlobalScope.launch {
            val contact = contacts.getContact() // suspended function
            withContext(Dispatchers.Default) { phoneContact.value = contact }
        }
    }

我只看到调度程序的默认,无限制和IO,但它们都不起作用,我不知道自己在做什么错?我的主线程选项在哪里?

I only see Default, Unconfined and IO for dispatchers, and none of them work, I can't figure out what I'm doing wrong? Where is my option for the Main Thread?

推荐答案

我在gradle文件中缺少协程的Android部分

I was missing the Android portion of coroutines in my gradle file

实施 "org.jetbrains.kotlinx:kotlinx-coroutines-android:0.30.0"

implementation "org.jetbrains.kotlinx:kotlinx-coroutines-android:0.30.0"

一旦我有了,Dispatchers.Main就出现了

Once I had that, Dispatchers.Main appeared

这篇关于如何在主线程上使用协程GlobalScope?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆