android - 我希望仅在收到实时数据后才调用函数
问题描述
我在android中使用实时数据。但我的问题是,在调用每个函数后最后才收到数据。在我的情况下,我的一个函数依赖于实时数据,但它在接收到实时数据之前被调用。我添加了评论让你更好地理解。请帮忙。
// polist is a MutableList
transactionDao.selectAll().observe(this, Observer {
if (it != null && it.isNotEmpty()) {
polist.addAll(it)
}
})
vregularDao.getAll().observe(this, Observer {
if (it != null && it.isNotEmpty()) {
polist.addAll(it)
}
})
// but this is called first then above codes.I want this to be called only after live data is received
alllist.forEach{
//perform some action
}
解决方案
您可能想查看线程。下面的代码在一个线程中运行,一旦有返回值,它就会被添加到polist
transactionDao.selectAll().observe(this, Observer {
if (it != null && it.isNotEmpty()) {
polist.addAll(it)
}
})
相同的
vregularDao.getAll().observe(this, Observer {
if (it != null && it.isNotEmpty()) {
polist.addAll(it)
}
})
因此最后一段代码被直接调用。因为其他两个线程目前还没有返回任何数据。
您需要创建某种阻止程序。
所以它会在列表枚举之后调用另一个函数,这并不优雅(PSUDEOCODE)......
bool selectAllDone;
bool getAllDone;
// polist is a MutableList
transactionDao.selectAll().observe(this, Observer {
if (it != null && it.isNotEmpty()) {
polist.addAll(it)
performSomeAction();
selectAllDone = true;
}
})
vregularDao.getAll().observe(this, Observer {
if (it != null && it.isNotEmpty()) {
polist.addAll(it)
performSomeAction();
getAllDone = true;
}
})
// but this is called first then above codes.I want this to be called only after live data is received
public fun performSomeAction(){
if(getAllDone & selectAllDone){
alllist.forEach{
//perform some action
}
}
}
推荐阅读
- c - 如何处理内存访问冲突?
- node.js - 如何在 Mocha 中创建具有特定大小的模拟帖子对象
- python - 纸浆调度优化问题 - 随着时间的推移,多个供应输入
- spring-rabbit - 仅为 rabbitmq 事件设置 MDC 属性
- spring - 查找具有角色(角色列表)的用户,该用户从列表中完全具有这些角色,而没有其他角色
- html2pdf - 如何将 html2pdf 与 crontab 一起使用?
- uber-api - Uber Universal Deep Link 给出 CORS 错误
- javascript - 使用 Functions Cloud 实现数据库数据
- mlflow - mlflow 异常:使用 UUID 运行已处于活动状态
- angular - Angular 8 ngStyle 有时在循环中不起作用