如何使用从coroutine外部的房间数据库发出的响应?
我需要使用coroutines来执行来自房间数据库的请求,然后将这些数据显示在回收视图中。我遇到的问题是,我无法从数据库中得到响应,无法在协同线之外显示。
我的密码。
class seconddisplay : AppCompatActivity(){
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.second_display)
GlobalScope.launch {
val respo = second_Database.getInstance(context = this@seconddisplay).DAO().seeAllcodes()
}
second_recyclerview.apply {
layoutManager = LinearLayoutManager(this@seconddisplay)
adapter = displayAdapter(respo)
}
}我也不能将回收视图代码放在coroutine中,因为它说您不能触摸视图的层次结构。
发布于 2020-07-09 06:13:48
在Activity或Fragment中,您可以使用lifecycleScope启动coroutine,默认情况下它运行在Main coroutine上下文中,因此您可以从那里更新UI:
lifecycleScope.launch {
// call like this if `seeAllcodes()` method is suspend
val respo = second_Database.getInstance(context = this@seconddisplay).DAO().seeAllcodes()
// call like this if `seeAllcodes()` method isn't suspend
val respo = withContext(Dispatchers.IO) { // runs on background thread
second_Database.getInstance(context = this@seconddisplay).DAO().seeAllcodes()
}
// update UI
second_recyclerview.apply {
layoutManager = LinearLayoutManager(this@seconddisplay)
if (respo != null) {
adapter = displayAdapter(respo)
}
}
}要使用lifecycleScope,请将下一行添加到应用程序的build.gradle文件的依赖项中:
implementation "androidx.lifecycle:lifecycle-runtime-ktx:2.3.0-alpha05"发布于 2020-07-09 02:37:21
您可以使用respo变量作为class.And的全局变量,然后使用属性withContext(Dispatcher.main)来使用主线程,然后像这样等待result.Something:
private var respo: YourDataType? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.second_display)
getRespo()
}
private fun getRespo(){
val supervisorJob = SupervisorJob()
val coroutineScope = CoroutineScope(Dispatchers.IO + supervisorJob)
coroutineScope.launch {
withContext(Dispatchers.Main) {
respo = second_Database.getInstance(this@seconddisplay).DAO().seeAllcodes()
second_recyclerview.apply {
layoutManager = LinearLayoutManager(this@seconddisplay)
if(respo!=null){
adapter = displayAdapter(respo)
}else{//handle respo being null, maybe show a message
}
}
}
}
}https://stackoverflow.com/questions/62806152
复制相似问题