首页 > 解决方案 > 我希望仅在收到实时数据后才调用函数

问题描述

我在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   
        }       

 

标签: androidkotlin

解决方案


您可能想查看线程。下面的代码在一个线程中运行,一旦有返回值,它就会被添加到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   
            }  
}
}

推荐阅读