我正在使用 Room,虽然我很高兴大多数查询都是异步的,但我有一个查询需要同步。
我似乎无法理解/实现暂停(即使这是正确的)。
关于如何使一个查询同步的建议会很好,因为我真的不想使用 sqlite。
Activity:需要同步的查询
Favourite fave = appDb.favouriteDao().findByTitle(formTitleText);
道:
@Dao
public interface FavouriteDao {
@Query("SELECT * FROM favourite")
List<Favourite> getAll();
@Insert
void insertFavourite(Favourite favourite);
@Update
void updateFavourite(Favourite favourite);
@Delete
void delete(Favourite favourite);
@Query("SELECT * FROM favourite WHERE calc_title LIKE :title LIMIT 1")
Favourite findByTitle(String title);
@Query("SELECT EXISTS(SELECT * FROM favourite WHERE calc_title LIKE :title LIMIT 1)")
boolean isRowIsExist(String title);
@Query("UPDATE favourite SET fav_status = :value WHERE calc_title LIKE :title")
void updateFavourite(String value, String title);
}
###更新###
按要求包含代码。基本上是一个 Firestore 查询,结果保存到计算器 ArrayList 中。除 setFormFavourite 之外,所有查询的 dataSection 变量都会添加到 ArrayList 中。因此,为什么我认为这一定是异步的(而且我读到的 Room 上的所有信息似乎都表明所有查询都是异步的)。
关于Suspend,不使用Kotlin,而是要注意。只是简单地提到它,因为将此视为确保房间查询完成的一种方法。但是,如果我的房间查询是同步的,那么我就迷失了为什么 dataSection.setFormFavourite(fave.getFav());在最终的calculators.add(dataSection)之前不返回;叫。它甚至没有添加为“null”,只是没有添加。 fave.getFav() 的 Log.d (直接放置在查询之后)似乎正确返回。 任何帮助表示赞赏
private void getCalculators(Source path) {
db.collection("Calculators")
.get(path)
.addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
public void onComplete(@NonNull Task<QuerySnapshot> task) {
if (task.isSuccessful()) {
for (QueryDocumentSnapshot document : task.getResult()) {
String formTitleText = (document.getString("title"));
String formTagLine = (document.getString("tagLine"));
String numberOfFields = (document.getString("NumberFields"));
String formInfo = (document.getString("formInfo"));
String formRef = (document.getString("formRef"));
String formula = (document.getString("formula"));
String resultUnits = (document.getString("resultUnits"));
String formSections = (document.getString("sections"));
Calculators dataSection = new Calculators();
dataSection.setFormTitleText(formTitleText);
dataSection.setFormTagLine(formTagLine);
dataSection.setNumberOfFields(numberOfFields);
dataSection.setFormInfo(formInfo);
dataSection.setFormRef(formRef);
dataSection.setFormula(formula);
dataSection.setResultUnits(resultUnits);
dataSection.setFormSections(formSections);
// add favourite status to room db
Favourite fave = appDb.favouriteDao().findByTitle(formTitleText);
dataSection.setFormFavourite(fave.getFav());
calculators.add(dataSection);